Skip to content

Bug on circular imports #1984

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
dmoisset opened this issue Aug 4, 2016 · 2 comments
Closed

Bug on circular imports #1984

dmoisset opened this issue Aug 4, 2016 · 2 comments

Comments

@dmoisset
Copy link
Contributor

dmoisset commented Aug 4, 2016

On certain situations with circular imports, some of the types defined on the circular import are not available, even as a comment/forward reference:

# bar.py
from typing import Union

import foo

MyType = Union[int, str]

# foo.py
import bar

x = ""  # type: bar.MyType

If I have these two files, then I get:

$ mypy bar.py
bar.py:3: note: In module imported here:
foo.py:3: error: Invalid type "bar.MyType"

(Note that this isn't a "MyType is an undefined name error, it's an "Invalid type"). I was expecting the bar.MyType reference to be possible.

This structure is quite similar to the one in #1972 (and came from the same piece of code), these issues might be related

@gvanrossum
Copy link
Member

Yeah, this is a general problem with import cycles. In this example, if you run mypy -v bar.py you should see that it processes foo.py entirely before processing bar.py.

The recommended work-around is to break the cycle by putting some imports inside functions. In your example, bar's import of foo seems less fundamental than foo's import of bar, so if you change bar to

def f():
    import foo
MyType = Union[int, str]

the error should disappear.

@ddfisher ddfisher added this to the Undetermined priority milestone Aug 4, 2016
@gvanrossum
Copy link
Member

Let's make this a duplicate of #481.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants