Lazy circular import with bottom import cannot determine type if the module name is alphabetically after the base class module
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
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
Baseis inb.py, any module named afterbalphabetically (i.e.,c,d,e, etc...) will fail to determine the type but nota.py. E.g., ifb.pywas insteadd.py, then botha.pyandc.pywill have the correct type. - The bottom imports and the
Baseimport incircular.pyare needed to reproduce this. If removed, this works.
Workaround
Explicitly add the type:
self._v: t.Final[str] = v or circular.v
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce the issue using the listed a.py, b.py, c.py, and circular.py files with mypy 1.15.0, then compare the inferred types for A and C. Trace the circular-import and bottom-import handling responsible for the alphabetical difference; done means both child classes infer _v consistently or fail consistently, with regression coverage for the example.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100