Skip to content

Commit d089f45

Browse files
authored
Only apply overloading union math to "real" unions (#5239)
By "real" unions I mean unions with more than one relevant item. Fixes #5238
1 parent 2f2f8e5 commit d089f45

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

mypy/checkexpr.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1129,7 +1129,8 @@ def check_overload_call(self,
11291129
erased_targets = None # type: Optional[List[CallableType]]
11301130
unioned_result = None # type: Optional[Tuple[Type, Type]]
11311131
unioned_errors = None # type: Optional[MessageBuilder]
1132-
if any(isinstance(arg, UnionType) for arg in arg_types):
1132+
if any(isinstance(arg, UnionType) and len(arg.relevant_items()) > 1 # "real" union
1133+
for arg in arg_types):
11331134
erased_targets = self.overload_erased_call_targets(plausible_targets, arg_types,
11341135
arg_kinds, arg_names, context)
11351136
unioned_callable = self.union_overload_matches(erased_targets)

test-data/unit/check-overloading.test

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3669,3 +3669,37 @@ reveal_type(Child.foo("...")) # E: Revealed type is 'builtins.str'
36693669
reveal_type(Child.foo(x)) # E: Revealed type is 'Union[Type[__main__.Child*], builtins.str]'
36703670
reveal_type(Child.foo(3)().child_only()) # E: Revealed type is 'builtins.int'
36713671
[builtins fixtures/classmethod.pyi]
3672+
3673+
[case testOptionalIsNotAUnionIfNoStrictOverload]
3674+
# flags: --no-strict-optional
3675+
from typing import Optional, overload
3676+
3677+
class B: pass
3678+
class C(B): pass
3679+
3680+
@overload
3681+
def rp(x: C) -> C: ...
3682+
@overload
3683+
def rp(x: B) -> B: ...
3684+
def rp(x):
3685+
pass
3686+
3687+
x: Optional[C]
3688+
reveal_type(rp(x)) # E: Revealed type is '__main__.C'
3689+
[out]
3690+
3691+
[case testOptionalIsNotAUnionIfNoStrictOverloadStr]
3692+
# flags: -2 --no-strict-optional
3693+
3694+
from typing import Optional
3695+
from m import relpath
3696+
a = '' # type: Optional[str]
3697+
reveal_type(relpath(a)) # E: Revealed type is 'builtins.str'
3698+
3699+
[file m.pyi]
3700+
from typing import overload
3701+
@overload
3702+
def relpath(path: str) -> str: ...
3703+
@overload
3704+
def relpath(path: unicode) -> unicode: ...
3705+
[out]

0 commit comments

Comments
 (0)