Skip to content

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

Closed

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

Activity

  1. sobolevn commented on Mar 1, 2023

    @sobolevn
    Member

    @AlexWaygood are you working on this? Or can I take this? :)

  2. AlexWaygood commented on Mar 1, 2023

    @AlexWaygood
    MemberAuthor

    Not working on it, feel free!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions