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

Allow iterable class objects to be unpacked #14803

Closed
wants to merge 11 commits into from

Conversation

AlexWaygood
Copy link
Member

Currently, mypy issues a false positive on this code, where Foo is iterable by virtue of having Meta as its metaclass:

from typing import Iterator
class Meta(type):
    def __iter__(cls) -> Iterator[int]:
        yield from [1, 2, 3]

class Foo(metaclass=Meta): ...

a, b, c = Foo  # error: "Type[Foo]" object is not iterable  [misc]
reveal_type(a)  # error: Cannot determine type of "a"  [has-type]  # note: Revealed type is "Any"

This PR fixes that false positive.

I started working on this PR hoping to address #14782, but wasn't able to -- this PR improves the situation somewhat, but doesn't close the issue. Prior to this PR, mypy had this behaviour:

from enum import Enum

class E(Enum):
    A = 1
    B = 2

A, B = E  #  error: "Type[E]" object is not iterable  [misc]

With this PR, mypy has this behaviour instead:

from enum import Enum

class E(Enum):
    A = 1
    B = 2

A, B = E  # error: Need type annotation for "A"  [var-annotated]  # error: Need type annotation for "B"  [var-annotated]

This is because there's a TypeVar being used in typeshed's stub for EnumMeta.__iter__: I wasn't able to figure out how to get mypy to solve the type variable in this context.

@github-actions

This comment has been minimized.

test-data/unit/check-inference.test Outdated Show resolved Hide resolved
mypy/checker.py Show resolved Hide resolved
@AlexWaygood AlexWaygood requested a review from sobolevn March 1, 2023 11:48
@github-actions

This comment has been minimized.

mypy/checker.py Outdated Show resolved Hide resolved
@github-actions

This comment has been minimized.

@github-actions
Copy link
Contributor

github-actions bot commented Mar 3, 2023

According to mypy_primer, this change has no effect on the checked open source code. 🤖🎉

@AlexWaygood AlexWaygood marked this pull request as draft March 3, 2023 11:59
@AlexWaygood
Copy link
Member Author

I found a much better solution, which also fixes the enum issue

@AlexWaygood AlexWaygood closed this Mar 3, 2023
@AlexWaygood AlexWaygood deleted the unpack-enum branch March 3, 2023 12:24
@AlexWaygood
Copy link
Member Author

AlexWaygood commented Mar 3, 2023

I found a much better solution, which also fixes the enum issue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants