diff --git a/mypy/typeanal.py b/mypy/typeanal.py index a513b0716a01..a9b4576c8f42 100644 --- a/mypy/typeanal.py +++ b/mypy/typeanal.py @@ -93,7 +93,6 @@ callable_with_ellipsis, find_unpack_in_list, flatten_nested_tuples, - flatten_nested_unions, get_proper_type, has_type_vars, ) @@ -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) diff --git a/test-data/unit/check-recursive-types.test b/test-data/unit/check-recursive-types.test index 84593933a2de..b67818e169b1 100644 --- a/test-data/unit/check-recursive-types.test +++ b/test-data/unit/check-recursive-types.test @@ -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]]]"