from typing import AnyStr, Generic, overload, Iterator
class Foo(Generic[AnyStr]):
x: AnyStr
@overload
def __iter__(self: Foo[str]) -> Iterator[bytes]: ...
@overload
def __iter__(self: Foo[bytes]) -> Iterator[str]: ...
def __iter__(self) -> Iterator[str | bytes]:
if isinstance(self.x, str):
yield from [b"a", b"b", b"c"]
yield from ["a", "b", "c"]
a, b, c = Foo[str]()
reveal_type(a) # note: Revealed type is "Any"
Mypy should have enough information here to infer that the type of a is bytes (and should probably ask for an explicit annotation if it can't infer that, rather than silently inferring Any).
Mypy version tested on