diff --git a/mypy/types.py b/mypy/types.py index b97937526ae4..1952585d58dd 100644 --- a/mypy/types.py +++ b/mypy/types.py @@ -858,9 +858,6 @@ def make_simplified_union(items: List[Type], line: int = -1, column: int = -1) - all_items.append(typ) items = all_items - if any(isinstance(typ, AnyType) for typ in items): - return AnyType() - from mypy.subtypes import is_subtype removed = set() # type: Set[int] for i, ti in enumerate(items): @@ -868,7 +865,11 @@ def make_simplified_union(items: List[Type], line: int = -1, column: int = -1) - # Keep track of the truishness info for deleted subtypes which can be relevant cbt = cbf = False for j, tj in enumerate(items): - if i != j and is_subtype(tj, ti): + # Attempt to only combine true subtypes by avoiding types containing Any. + # TODO: Properly exclude generics and functions. + tj_is_anylike = (isinstance(tj, AnyType) or + (isinstance(tj, Instance) and tj.type.fallback_to_any)) + if i != j and is_subtype(tj, ti) and not tj_is_anylike: removed.add(j) cbt = cbt or tj.can_be_true cbf = cbf or tj.can_be_false diff --git a/test-data/unit/check-optional.test b/test-data/unit/check-optional.test index 010ab8f9eef5..4b8f3104256d 100644 --- a/test-data/unit/check-optional.test +++ b/test-data/unit/check-optional.test @@ -428,3 +428,10 @@ x + 1 [out] main:2: note: In module imported here: tmp/a.py:3: error: Unsupported left operand type for + (some union) + +[case testOptionalFallbackToNone] +from typing import Any, Optional +class C(Any): + pass +x = None # type: Optional[C] +x.foo() # E: Some element of union has no attribute "foo"