Skip to content

Unpacking an iterable with an overloaded __iter__ method leads to variable silently being inferred as Any #14811

Closed
@AlexWaygood

Description

@AlexWaygood
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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions