Skip to content

Commit 3b331b3

Browse files
authored
Fix "Implicit type aliases not recognised with PEP 604 + import cycles" (but only for stubs) (#11915)
1 parent 080bb0e commit 3b331b3

File tree

2 files changed

+35
-5
lines changed

2 files changed

+35
-5
lines changed

mypy/semanal.py

+8-5
Original file line numberDiff line numberDiff line change
@@ -2177,11 +2177,14 @@ def can_be_type_alias(self, rv: Expression, allow_none: bool = False) -> bool:
21772177
return True
21782178
if allow_none and isinstance(rv, NameExpr) and rv.fullname == 'builtins.None':
21792179
return True
2180-
if (isinstance(rv, OpExpr)
2181-
and rv.op == '|'
2182-
and self.can_be_type_alias(rv.left, allow_none=True)
2183-
and self.can_be_type_alias(rv.right, allow_none=True)):
2184-
return True
2180+
if isinstance(rv, OpExpr) and rv.op == '|':
2181+
if self.is_stub_file:
2182+
return True
2183+
if (
2184+
self.can_be_type_alias(rv.left, allow_none=True)
2185+
and self.can_be_type_alias(rv.right, allow_none=True)
2186+
):
2187+
return True
21852188
return False
21862189

21872190
def is_type_ref(self, rv: Expression, bare: bool = False) -> bool:

test-data/unit/check-union-or-syntax.test

+27
Original file line numberDiff line numberDiff line change
@@ -196,3 +196,30 @@ def f(x: Union[int, str, None]) -> None:
196196
else:
197197
reveal_type(x) # N: Revealed type is "None"
198198
[builtins fixtures/isinstance.pyi]
199+
200+
[case testImplicit604TypeAliasWithCyclicImportInStub]
201+
# flags: --python-version 3.10
202+
from was_builtins import foo
203+
reveal_type(foo) # N: Revealed type is "Union[builtins.str, was_mmap.mmap]"
204+
[file was_builtins.pyi]
205+
import was_mmap
206+
WriteableBuffer = was_mmap.mmap
207+
ReadableBuffer = str | WriteableBuffer
208+
foo: ReadableBuffer
209+
[file was_mmap.pyi]
210+
from was_builtins import *
211+
class mmap: ...
212+
213+
# TODO: Get this test to pass
214+
[case testImplicit604TypeAliasWithCyclicImportNotInStub-xfail]
215+
# flags: --python-version 3.10
216+
from was_builtins import foo
217+
reveal_type(foo) # N: Revealed type is "Union[builtins.str, was_mmap.mmap]"
218+
[file was_builtins.py]
219+
import was_mmap
220+
WriteableBuffer = was_mmap.mmap
221+
ReadableBuffer = str | WriteableBuffer
222+
foo: ReadableBuffer
223+
[file was_mmap.py]
224+
from was_builtins import *
225+
class mmap: ...

0 commit comments

Comments
 (0)