Simple module with harmless import cycle results in Cannot determine type error #6312
Copy link
Copy link
Closed
Labels
bugmypy got something wrongmypy got something wrongfalse-positivemypy gave an error on correct codemypy gave an error on correct codepriority-1-normaltopic-import-cyclestopic-usability
Description
To repro (I'm using mypy 0.660):
In models/__init__.py:
config = object()
from .user import User
In models/user.py:
from . import config
print(config)
class User: ...
It runs fine:
~/tmp/repro$ python3 -c 'import models'
<object object at 0x10eccb1c0>
But mypy fails:
~/tmp/repro$ mypy -m models
models/user.py:2: error: Cannot determine type of 'config'
There are two issues here (I'm happy to file another one to track them separately if that helps):
- This should probably be supported by mypy
- Regardless of whether this particular case is fixed, the error message should say something about import cycles (looks like there have been several issues similar to this in the past; this probably won't be the last)
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
bugmypy got something wrongmypy got something wrongfalse-positivemypy gave an error on correct codemypy gave an error on correct codepriority-1-normaltopic-import-cyclestopic-usability
Activity
ilevkivskyi commentedon Feb 7, 2019
Import cycles are never harmless :-)
Unfortunately, it is very hard to allow this without also allowing code that will fail at runtime (for example if you move the import in the first file to the top). But I agree that we should at least give a better error message.
See also #6356 for more general discussion.
russelldavis commentedon Feb 7, 2019
Thanks for the reply.
I agree that mypy shouldn't allow cycles that will fail at runtime. I linked to several other issues with runtime-safe cycles that seem to have been fixed. I'm curious why this one different.
Wouldn't it be possible for mypy to keep track of the attributes that have been assigned to a module mid-way through the cycle (essentially mirroring what happens at runtime)?
I think the pattern in the example shown is actually pretty common in practice, where people organize their code in a class-per-file style, and want to make the classes available in the parent module (so they can, e.g.,
import models.Userinstead ofmodels.user.User).ilevkivskyi commentedon Sep 24, 2019
This is essentially a duplicate of #6356 (actually vice-versa, but the other issue is a more generic one). I am closing this one and raising priority for other one.