Skip to content
Open
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
14 changes: 13 additions & 1 deletion mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -6413,7 +6413,19 @@ def visit_yield_from_expr(self, e: YieldFromExpr, allow_none_return: bool = Fals
# Check that the iterator's item type matches the type yielded by the Generator function
# containing this `yield from` expression.
expected_item_type = self.chk.get_generator_yield_type(return_type, False)
actual_item_type = self.chk.get_generator_yield_type(iter_type, False)
proper_iter_type = get_proper_type(iter_type)
if (
isinstance(proper_iter_type, Instance)
and not self.chk.is_generator_return_type(proper_iter_type, is_coroutine=False)
and not self.chk.is_async_generator_return_type(proper_iter_type)
and self.chk.type_is_iterable(proper_iter_type)
):
# A concrete Iterable/Iterator subclass isn't one of the generator types, and its item
# type isn't necessarily its first type argument (e.g. enumerate), so map it to Iterable
# the way a `for` loop does instead of falling back to Any.
actual_item_type = self.chk.iterable_item_type(proper_iter_type, e)
else:
actual_item_type = self.chk.get_generator_yield_type(iter_type, False)

self.chk.check_subtype(
actual_item_type,
Expand Down
26 changes: 26 additions & 0 deletions test-data/unit/check-statements.test
Original file line number Diff line number Diff line change
Expand Up @@ -1349,6 +1349,32 @@ def f() -> Iterator[str]:
yield from h() # E: Incompatible types in "yield from" (actual type "int", expected type "str")
[out]

[case testYieldFromIteratorSubclass]
# https://github.com/python/mypy/issues/17449
from typing import Iterator, Tuple, TypeVar
T = TypeVar("T")

class Ints(Iterator[int]):
def __next__(self) -> int: ...
def __iter__(self) -> "Ints": ...

def bad() -> Iterator[str]:
yield from Ints() # E: Incompatible types in "yield from" (actual type "int", expected type "str")
def good() -> Iterator[int]:
yield from Ints()

# The item type is not the first type argument, so a naive args[0] would be wrong here.
class Pairs(Iterator[Tuple[int, T]]):
def __next__(self) -> Tuple[int, T]: ...
def __iter__(self) -> "Pairs[T]": ...

def pairs_good() -> Iterator[Tuple[int, str]]:
yield from Pairs[str]()
def pairs_bad() -> Iterator[str]:
yield from Pairs[str]() # E: Incompatible types in "yield from" (actual type "tuple[int, str]", expected type "str")
[builtins fixtures/tuple.pyi]
[out]

[case testYieldFromAppliedToAny]
from typing import Any
def g() -> Any:
Expand Down
Loading