Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
AlexWaygood opened this issue Mar 1, 2023 · 2 comments · Fixed by #14817
Labels
bug mypy got something wrong topic-overloads

Comments

@AlexWaygood
Copy link
Member

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

@sobolevn
Copy link
Member

sobolevn commented Mar 1, 2023

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

@AlexWaygood
Copy link
Member Author

Not working on it, feel free!

JukkaL pushed a commit that referenced this issue Mar 2, 2023
The change is quite simple: instead of manually unpacking the return
type of `find_item`, we use the regular machinery for it.

Note, that this PR does not include any metaclasses related work. We
still have problems with them, but I will defer them to the next PR.

Closes #14811
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-overloads
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants