Sub topic 12
Creating enums with the functional API
This chapter assumes you can define a class-based Enum, read .name and .value, and look members up with Color(2) and Color["BLUE"]. It also assumes you know what auto() does.
What the functional API is
The class statement is not the only way to create an enum. You can also call Enum like a function and pass it the class name and the member names. This is the functional API. It is useful when the members are not known until the program runs, for example when they come from a config file or a database table.
from enum import Enum
Animal = Enum("Animal", "ANT BEE CAT")
print(list(Animal)) # [<Animal.ANT: 1>, <Animal.BEE: 2>, <Animal.CAT: 3>]The first argument is the name of the new class. Assign the result to a variable with the same name. Python does not check that the two match, but a mismatch makes repr() output and error messages confusing.
Ways to give the member names
The second argument can take four forms.
| Form | Example | Values |
|---|---|---|
| String of names | `"ANT BEE CAT"` | Numbered from 1 |
| Sequence of names | `["ANT", "BEE", "CAT"]` | Numbered from 1 |
| Sequence of `(name, value)` pairs | `[("OK", 200), ("NOT_FOUND", 404)]` | Taken from the pairs |
| Mapping of name to value | `{"OK": 200, "NOT_FOUND": 404}` | Taken from the mapping |
In a string, names can be separated by spaces or commas. The next example shows the last three forms.
from enum import Enum
Zero = Enum("Zero", ["ANT", "BEE"], start=0)
print(list(Zero)) # [<Zero.ANT: 0>, <Zero.BEE: 1>]
Http = Enum("Http", [("OK", 200), ("NOT_FOUND", 404)])
print(Http(404)) # Http.NOT_FOUND
Level = Enum("Level", {"LOW": "low", "HIGH": "high"})
print(Level["HIGH"].value) # highThe start keyword changes the first automatic number. It has no effect when you supply the values yourself.
Building an enum from data
The mapping form is the most practical one. Suppose the allowed colors come from a list of strings loaded at startup.
from enum import Enum
names = ["red", "green", "blue"]
Color = Enum("Color", {n.upper(): n for n in names})
print(Color("green")) # Color.GREEN
print([c.name for c in Color]) # ['RED', 'GREEN', 'BLUE']You get the same lookup, iteration and comparison behavior as a class-based enum. The one drawback is that static type checkers cannot see members created at runtime. They will flag Color.RED as unknown, so prefer a class statement when the members are fixed.
Other mixins and the module argument
To get an IntEnum or StrEnum with the functional API, call that class instead of Enum.
from enum import IntEnum
Priority = IntEnum("Priority", "LOW MEDIUM HIGH")
print(Priority.HIGH > Priority.LOW) # True
print(Priority.MEDIUM == 2) # TruePickling is where the functional API can fail. To pickle a member, Python must be able to import the class by its module and name. Python tries to detect the calling module, but this can fail in some environments. Pass module=__name__ to set it explicitly.
import pickle
from enum import Enum
Animal = Enum("Animal", "ANT BEE CAT", module=__name__)
data = pickle.dumps(Animal.BEE)
print(pickle.loads(data) is Animal.BEE) # TrueIf the class is not created at module level, also set qualname to the dotted path where it can be found.
Common errors
- Names that are not valid identifiers. A name such as
"1st"works in a mapping, but you can only reach the member withEnum["1st"], not with attribute access. - Duplicate values. The functional API follows the same alias rules as the class form. A repeated value creates an alias, not a new member.
@uniquecan be applied afterward withunique(MyEnum). - Expecting methods. The functional API cannot define methods or properties. Use a class statement when you need them.
Exercise
Write a call to the functional API that creates an enum named Size with members SMALL, MEDIUM and LARGE, numbered from 10 instead of 1. What is Size.LARGE.value?
Show answer
Use Size = Enum("Size", "SMALL MEDIUM LARGE", start=10). The members get the values 10, 11 and 12, so Size.LARGE.value is 12.