Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 2562140

Browse files
authored
Allow recursive aliases at class scope (#13754)
As `mypy_primer` in #13516 shows, some people actually use this, and I don't see any good reason to not allow this. (Note: I tried to enable the same for recursive NamedTuples and TypedDicts, but this affects how nested classes work in general, so people will need to use qualified names there).
1 parent 9783b46 commit 2562140

2 files changed

Lines changed: 20 additions & 2 deletions

File tree

mypy/semanal.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5086,7 +5086,9 @@ class C:
50865086
X = X # Initializer refers to outer scope
50875087
50885088
Nested classes are an exception, since we want to support
5089-
arbitrary forward references in type annotations.
5089+
arbitrary forward references in type annotations. Also, we
5090+
allow forward references to type aliases to support recursive
5091+
types.
50905092
"""
50915093
# TODO: Forward reference to name imported in class body is not
50925094
# caught.
@@ -5097,7 +5099,7 @@ class C:
50975099
node is None
50985100
or self.is_textually_before_statement(node)
50995101
or not self.is_defined_in_current_module(node.fullname)
5100-
or isinstance(node, TypeInfo)
5102+
or isinstance(node, (TypeInfo, TypeAlias))
51015103
or (isinstance(node, PlaceholderNode) and node.becomes_typeinfo)
51025104
)
51035105

test-data/unit/check-recursive-types.test

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -810,3 +810,19 @@ std: STD[str]
810810
reveal_type(std) # N: Revealed type is "TypedDict('__main__.STD', {'val': builtins.str, 'other': ..., 'sval': builtins.str, 'one': TypedDict('__main__.TD', {'val': builtins.str, 'other': ...})})"
811811
[builtins fixtures/dict.pyi]
812812
[typing fixtures/typing-typeddict.pyi]
813+
814+
[case testRecursiveClassLevelAlias]
815+
# flags: --enable-recursive-aliases
816+
from typing import Union, Sequence
817+
818+
class A:
819+
Children = Union[Sequence['Children'], 'A', None]
820+
x: A.Children
821+
reveal_type(x) # N: Revealed type is "Union[typing.Sequence[...], __main__.A, None]"
822+
823+
class B:
824+
Foo = Sequence[Bar]
825+
Bar = Sequence[Foo]
826+
y: B.Foo
827+
reveal_type(y) # N: Revealed type is "typing.Sequence[typing.Sequence[...]]"
828+
[builtins fixtures/tuple.pyi]

0 commit comments

Comments
 (0)