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 (including enums) #14827

Merged
merged 3 commits into from
Mar 6, 2023

Conversation

AlexWaygood
Copy link
Member

Fixes #14782

Currently, mypy issues a false positive if you try to unpack an enum class:

from enum import Enum

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

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

This is because of a more general problem with class objects that have __iter__ defined on their metaclass. 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 the false positive with enums, and the more general false positive with iterable class objects.

@github-actions

This comment has been minimized.

Copy link
Collaborator

@JukkaL JukkaL left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good! I like the detailed test coverage. The only potential issue I see is overloaded __init__ methods.

mypy/checker.py Outdated Show resolved Hide resolved
test-data/unit/check-inference.test Show resolved Hide resolved
@AlexWaygood
Copy link
Member Author

AlexWaygood commented Mar 3, 2023

Looks good! I like the detailed test coverage. The only potential issue I see is overloaded __init__ methods.

Good catch, that did indeed fail unnecessarily! Addressed in the latest commit.

@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 requested a review from JukkaL March 3, 2023 14:50
Copy link
Collaborator

@JukkaL JukkaL left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great that enum unpacking now works!

@JukkaL JukkaL merged commit b6cb0ed into python:master Mar 6, 2023
@AlexWaygood AlexWaygood deleted the unpack-enum2 branch March 6, 2023 17:16
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.

Unpacking enum type generates an error
2 participants