python / python/mypy

Support functional API for Enum *Subclasses* too

Open
#6,037 1 comment 20 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature topic-enum
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Tested with version 0.641.

The functional API for enums is only supported on Enum itself, and not subclasses (that do not override the relevant methods). I hit this using the OrderedEnum suggestion from the standard library documentation: https://docs.python.org/3/library/enum.html#orderedenum.

Running on:

from enum import Enum

class Foo(Enum):
    ""

Bar: type = Enum('Bar', ['X', 'Y']) # line 6
Baz: type = Foo('Baz', ['X', 'Y']) # line 7

bar: Bar = Bar.X # line 9
baz: Baz = Baz.Y # line 10

gives

asdf.py:7: error: Incompatible types in assignment (expression has type "Foo", variable has type "type")
asdf.py:7: error: Too many arguments for "Foo"
asdf.py:10: error: Invalid type "asdf.Baz"
asdf.py:10: error: "type" has no attribute "Y"

Note that 6 is deemed fine, but 7 causes complaints. I'd hope for both lines to be fine.

The even larger issue is that annotations using Baz totally fail too: Line 9 is deemed fine but 10 fails. I wouldn't mind the obscure use of the Enum subclass failing if it weren't for the fact that every annotation with my nice enum type won't work.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the reproducer in the issue and trace mypy's handling of the Enum functional API for Enum subclasses. Check how the inferred type of Foo('Baz', ['X', 'Y']) and annotations using Baz are processed. Done means both the subclass factory call and members typed as Baz type-check without the reported errors.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.