Skip to content

Commit

Permalink
Fix crash on recursive alias with an optional type (#17350)
Browse files Browse the repository at this point in the history
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>
  • Loading branch information
ilevkivskyi and pre-commit-ci[bot] committed Jun 9, 2024
1 parent 3518f24 commit 428a035
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 9 deletions.
12 changes: 3 additions & 9 deletions mypy/typeanal.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,6 @@
callable_with_ellipsis,
find_unpack_in_list,
flatten_nested_tuples,
flatten_nested_unions,
get_proper_type,
has_type_vars,
)
Expand Down Expand Up @@ -2337,16 +2336,11 @@ def make_optional_type(t: Type) -> Type:
is called during semantic analysis and simplification only works during
type checking.
"""
p_t = get_proper_type(t)
if isinstance(p_t, NoneType):
if isinstance(t, ProperType) and isinstance(t, NoneType):
return t
elif isinstance(p_t, UnionType):
elif isinstance(t, ProperType) and isinstance(t, UnionType):
# Eagerly expanding aliases is not safe during semantic analysis.
items = [
item
for item in flatten_nested_unions(p_t.items, handle_type_alias_type=False)
if not isinstance(get_proper_type(item), NoneType)
]
items = [item for item in t.items if not isinstance(get_proper_type(item), NoneType)]
return UnionType(items + [NoneType()], t.line, t.column)
else:
return UnionType([t, NoneType()], t.line, t.column)
Expand Down
16 changes: 16 additions & 0 deletions test-data/unit/check-recursive-types.test
Original file line number Diff line number Diff line change
Expand Up @@ -942,3 +942,19 @@ NotFilter = Tuple[Literal["not"], "NotFilter"]
n: NotFilter
reveal_type(n[1][1][0]) # N: Revealed type is "Literal['not']"
[builtins fixtures/tuple.pyi]

[case testNoCrashOnRecursiveAliasWithNone]
# flags: --strict-optional
from typing import Union, Generic, TypeVar, Optional

T = TypeVar("T")
class A(Generic[T]): ...
class B(Generic[T]): ...

Z = Union[A[Z], B[Optional[Z]]]
X = Union[A[Optional[X]], B[Optional[X]]]

z: Z
x: X
reveal_type(z) # N: Revealed type is "Union[__main__.A[...], __main__.B[Union[..., None]]]"
reveal_type(x) # N: Revealed type is "Union[__main__.A[Union[..., None]], __main__.B[Union[..., None]]]"

0 comments on commit 428a035

Please sign in to comment.