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

Support enums in unions per PEP 484 #1803

Closed
gvanrossum opened this issue Jul 5, 2016 · 2 comments · Fixed by #7000
Closed

Support enums in unions per PEP 484 #1803

gvanrossum opened this issue Jul 5, 2016 · 2 comments · Fixed by #7000

Comments

@gvanrossum
Copy link
Member

See this PR for PEP 484: python/typing#240

Because we know that Enum classes cannot be further subclassed, picking apart a value that could be a specific enum or some other type by comparing to all possible values of the enum should be enough to conclude that in the "else" clause the value cannot be an instance of that enum any more, so it must be the other type (examples in the linked PEP section).

@gvanrossum
Copy link
Member Author

This should work for other singletons, specifically Ellipsis. (Though it's unclear how its type should be spelled since builtins.ellipsis only exists in the stubs, not in the actual runtime.)

@gvanrossum gvanrossum removed this from the 0.5 milestone Mar 29, 2017
@ilevkivskyi
Copy link
Member

It looks like this would be easier to implement after we support literal types.

ilevkivskyi pushed a commit that referenced this issue Jul 8, 2019
Fixes #1803

This diff adds support for performing reachability and narrowing analysis when doing certain enum checks.

For example, given the following enum:

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

...this pull request will make mypy do the following:

    x: Foo
    if x is Foo.A:
        reveal_type(x)  # type: Literal[Foo.A]
    elif x is Foo.B:
        reveal_type(x)  # type: Literal[Foo.B]
    else:
        reveal_type(x)  # No output: branch inferred as unreachable

This diff does not attempt to perform this same sort of narrowing for equality checks: I suspect implementing those will be harder due to their overridable nature. (E.g. you can define custom `__eq__` methods within Enum subclasses).

This pull request also finally adds support for the enum behavior [described in PEP 484][0] and also sort of partially addresses #6366

  [0]: https://www.python.org/dev/peps/pep-0484/#support-for-singleton-types-in-unions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants