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

Fix "Implicit type aliases not recognised with PEP 604 + import cycles" (but only for stubs) #11915

Merged
merged 8 commits into from
Jan 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions mypy/semanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -2177,11 +2177,14 @@ def can_be_type_alias(self, rv: Expression, allow_none: bool = False) -> bool:
return True
if allow_none and isinstance(rv, NameExpr) and rv.fullname == 'builtins.None':
return True
if (isinstance(rv, OpExpr)
and rv.op == '|'
and self.can_be_type_alias(rv.left, allow_none=True)
and self.can_be_type_alias(rv.right, allow_none=True)):
return True
if isinstance(rv, OpExpr) and rv.op == '|':
if self.is_stub_file:
return True
if (
self.can_be_type_alias(rv.left, allow_none=True)
and self.can_be_type_alias(rv.right, allow_none=True)
):
return True
return False

def is_type_ref(self, rv: Expression, bare: bool = False) -> bool:
Expand Down
27 changes: 27 additions & 0 deletions test-data/unit/check-union-or-syntax.test
Original file line number Diff line number Diff line change
Expand Up @@ -196,3 +196,30 @@ def f(x: Union[int, str, None]) -> None:
else:
reveal_type(x) # N: Revealed type is "None"
[builtins fixtures/isinstance.pyi]

[case testImplicit604TypeAliasWithCyclicImportInStub]
# flags: --python-version 3.10
from was_builtins import foo
reveal_type(foo) # N: Revealed type is "Union[builtins.str, was_mmap.mmap]"
[file was_builtins.pyi]
import was_mmap
WriteableBuffer = was_mmap.mmap
ReadableBuffer = str | WriteableBuffer
foo: ReadableBuffer
[file was_mmap.pyi]
from was_builtins import *
class mmap: ...

# TODO: Get this test to pass
[case testImplicit604TypeAliasWithCyclicImportNotInStub-xfail]
# flags: --python-version 3.10
from was_builtins import foo
reveal_type(foo) # N: Revealed type is "Union[builtins.str, was_mmap.mmap]"
[file was_builtins.py]
import was_mmap
WriteableBuffer = was_mmap.mmap
ReadableBuffer = str | WriteableBuffer
foo: ReadableBuffer
[file was_mmap.py]
from was_builtins import *
class mmap: ...