Skip to content

Commit 041aa5d

Browse files
Document undesirable generator expression behavior in test and fix one case (#20594)
Adds a test case to explicitly demonstrate behavior which I believe has the same root cause as #18026 The short explanation is that if _any_ get produced while inferring the type of a generator expression which is being passed to an overloaded function, the overload will be considered failed, even if the error has no effect on the inferred type of the generator expression. One experiment to try that might address this could be to only fail the overload if the inferred type contains `AnyType(TypeOfAny.from_error)`. For now, only fix the specific case where the "error" is a `reveal_type` note.
1 parent 33c0d0a commit 041aa5d

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

mypy/checkexpr.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2918,7 +2918,7 @@ def infer_overload_return_type(
29182918

29192919
for typ in plausible_targets:
29202920
assert self.msg is self.chk.msg
2921-
with self.msg.filter_errors() as w:
2921+
with self.msg.filter_errors(filter_revealed_type=True) as w:
29222922
with self.chk.local_type_map as m:
29232923
ret_type, infer_type = self.check_call(
29242924
callee=typ,

test-data/unit/check-expressions.test

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1456,6 +1456,27 @@ if int():
14561456
b = (x for x in a) # E: Generator has incompatible item type "Callable[[], str]"; expected "Callable[[], int]"
14571457
[builtins fixtures/list.pyi]
14581458

1459+
[case testGeneratorNoSpuriousError]
1460+
from typing import Iterable, overload
1461+
1462+
@overload
1463+
def take_iterable(iterable: Iterable[bool], /) -> None: ...
1464+
@overload
1465+
def take_iterable(iterable: Iterable[int], /) -> None: ...
1466+
def take_iterable(iterable): pass
1467+
1468+
take_iterable(1 for _ in [])
1469+
take_iterable(reveal_type(1 for _ in [])) # N: Revealed type is "typing.Generator[builtins.int, None, None]"
1470+
1471+
# NOTE: Type is revealed for every overload tried
1472+
# TODO: Overload shouldn't fail if expression contains an error that shouldn't affect the inferred type.
1473+
take_iterable(reveal_type(1 if (-"") else 1 for _ in [])) # N: Revealed type is "typing.Generator[builtins.int, None, None]" \
1474+
# N: Revealed type is "typing.Generator[builtins.bool, None, None]" \
1475+
# E: Generator has incompatible item type "int"; expected "bool" \
1476+
# E: Unsupported operand type for unary - ("str")
1477+
1478+
[builtins fixtures/for.pyi]
1479+
14591480
-- Conditional expressions
14601481
-- -----------------------
14611482

0 commit comments

Comments
 (0)