Skip to content

Simple module with harmless import cycle results in Cannot determine type error #6312

Closed

Description

@russelldavis

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):

  1. This should probably be supported by mypy
  2. 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)

Related issues:
#2015
#2016
#1185
#481

Activity

  1. ilevkivskyi commented on Feb 7, 2019

    @ilevkivskyi
    Member

    harmless import cycle

    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.

  2. russelldavis commented on Feb 7, 2019

    @russelldavis
    Author

    Thanks for the reply.

    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).

    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.User instead of models.user.User).

  3. ilevkivskyi commented on Sep 24, 2019

    @ilevkivskyi
    Member

    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.

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions