Skip to content

Commit f9354eb

Browse files
committed
Fix incorrect type inference for with iterators
1 parent f3e2a97 commit f9354eb

2 files changed

Lines changed: 21 additions & 2 deletions

File tree

mypy/checkexpr.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""Expression type checker. This file is conceptually part of TypeChecker."""
2-
32
from __future__ import annotations
3+
from mypy.types import Instance
4+
from mypy.types import Instance, get_proper_type
45

56
import enum
67
import itertools
@@ -6273,7 +6274,14 @@ def visit_yield_from_expr(self, e: YieldFromExpr, allow_none_return: bool = Fals
62736274
# Check that the iterator's item type matches the type yielded by the Generator function
62746275
# containing this `yield from` expression.
62756276
expected_item_type = self.chk.get_generator_yield_type(return_type, False)
6276-
actual_item_type = self.chk.get_generator_yield_type(iter_type, False)
6277+
6278+
6279+
iter_type_proper = get_proper_type(iter_type)
6280+
6281+
if isinstance(iter_type_proper, Instance) and iter_type_proper.args:
6282+
actual_item_type = iter_type_proper.args[0]
6283+
else:
6284+
actual_item_type = self.chk.get_generator_yield_type(iter_type, False)
62776285

62786286
self.chk.check_subtype(
62796287
actual_item_type,

test-data/unit/check-functions.test

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3768,3 +3768,14 @@ class C:
37683768

37693769
def defer() -> int:
37703770
return 1
3771+
3772+
3773+
[case testYieldFromIteratorMismatch]
3774+
from typing import Generator, Iterator
3775+
3776+
class A(Iterator[int]):
3777+
def __next__(self) -> int: ...
3778+
def __iter__(self) -> "A": ...
3779+
3780+
def f() -> Generator[tuple[int, ...], None, None]:
3781+
yield from A() # E: Incompatible types in "yield"

0 commit comments

Comments
 (0)