Skip to content

Commit 428a035

Browse files
Fix crash on recursive alias with an optional type (#17350)
Fixes #17132 Fix is trivial, we don't need that extra `get_proper_type()`. --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 3518f24 commit 428a035

File tree

2 files changed

+19
-9
lines changed

2 files changed

+19
-9
lines changed

mypy/typeanal.py

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,6 @@
9393
callable_with_ellipsis,
9494
find_unpack_in_list,
9595
flatten_nested_tuples,
96-
flatten_nested_unions,
9796
get_proper_type,
9897
has_type_vars,
9998
)
@@ -2337,16 +2336,11 @@ def make_optional_type(t: Type) -> Type:
23372336
is called during semantic analysis and simplification only works during
23382337
type checking.
23392338
"""
2340-
p_t = get_proper_type(t)
2341-
if isinstance(p_t, NoneType):
2339+
if isinstance(t, ProperType) and isinstance(t, NoneType):
23422340
return t
2343-
elif isinstance(p_t, UnionType):
2341+
elif isinstance(t, ProperType) and isinstance(t, UnionType):
23442342
# Eagerly expanding aliases is not safe during semantic analysis.
2345-
items = [
2346-
item
2347-
for item in flatten_nested_unions(p_t.items, handle_type_alias_type=False)
2348-
if not isinstance(get_proper_type(item), NoneType)
2349-
]
2343+
items = [item for item in t.items if not isinstance(get_proper_type(item), NoneType)]
23502344
return UnionType(items + [NoneType()], t.line, t.column)
23512345
else:
23522346
return UnionType([t, NoneType()], t.line, t.column)

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

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -942,3 +942,19 @@ NotFilter = Tuple[Literal["not"], "NotFilter"]
942942
n: NotFilter
943943
reveal_type(n[1][1][0]) # N: Revealed type is "Literal['not']"
944944
[builtins fixtures/tuple.pyi]
945+
946+
[case testNoCrashOnRecursiveAliasWithNone]
947+
# flags: --strict-optional
948+
from typing import Union, Generic, TypeVar, Optional
949+
950+
T = TypeVar("T")
951+
class A(Generic[T]): ...
952+
class B(Generic[T]): ...
953+
954+
Z = Union[A[Z], B[Optional[Z]]]
955+
X = Union[A[Optional[X]], B[Optional[X]]]
956+
957+
z: Z
958+
x: X
959+
reveal_type(z) # N: Revealed type is "Union[__main__.A[...], __main__.B[Union[..., None]]]"
960+
reveal_type(x) # N: Revealed type is "Union[__main__.A[Union[..., None]], __main__.B[Union[..., None]]]"

0 commit comments

Comments
 (0)