Skip to content
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

Lazy circular import with bottom import cannot determine type if the module name is alphabetically after the base class module #18734

Open
nelsyeung opened this issue Feb 25, 2025 · 0 comments
Labels
bug mypy got something wrong topic-import-cycles

Comments

@nelsyeung
Copy link

To Reproduce

mkdir mypyissue
cd mypyissue
touch __init__.py a.py b.py c.py circular.py py.typed

a.py:

import typing_extensions as t
from .b import Base
class A(Base):
    def run(self) -> None:
        t.reveal_type(self._v)

b.py:

import typing as t
class Base:
    def __init__(self, v: t.Optional[str] = None) -> None:
        from .circular import circular
        self._v: t.Final = v or circular.v
from .a import A
from .c import C

c.py:

import typing_extensions as t
from .b import Base
class C(Base):
    def run(self) -> None:
        t.reveal_type(self._v)

circular.py

from .b import Base
class Circular:
    @property
    def v(self) -> str:
        return "value"
circular = Circular()

Expected Behavior

self._v to have the correct type for all children. Or at least consistently fail rather than now where somehow the module name matters.

Actual Behavior

c.py:5: error: Cannot determine type of "_v"  [has-type]
c.py:5: note: Revealed type is "Any"
a.py:5: note: Revealed type is "builtins.str"
Found 1 error in 1 file (checked 5 source files)

Notice that a.py has the correct type but not c.py.

Your Environment

  • Mypy version used: mypy 1.15.0 (compiled: yes)
  • Mypy command-line flags: Nothing
  • Mypy configuration options from mypy.ini (and other config files): Nothing
  • Python version used: 3.9.19

Additional notes

  • Pyright works in this case.
  • The first character of the file name is important. In this case, since Base is in b.py, any module named after b alphabetically (i.e., c, d, e, etc...) will fail to determine the type but not a.py. E.g., if b.py was instead d.py, then both a.py and c.py will have the correct type.
  • The bottom imports and the Base import in circular.py are needed to reproduce this. If removed, this works.

Workaround

Explicitly add the type:

self._v: t.Final[str] = v or circular.v
@nelsyeung nelsyeung added the bug mypy got something wrong label Feb 25, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-import-cycles
Projects
None yet
Development

No branches or pull requests

2 participants