Skip to content
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
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]]]"