Sub topic 12
Creating enums with the functional API
This chapter assumes you can write a class-based Enum, know that members have .name and .value, and understand how aliases and auto() assign values. You also need to be comfortable calling a class to create an object. Here you will build enums by calling Enum like a function instead of writing a class statement.
Why a second way to define enums exists
The class syntax is the right default. It reads well, and type checkers and IDEs understand it. It has one limit: member names must be written in the source code. Sometimes the names only exist at runtime, for example when they come from a configuration file, a database table, or a list of column headers.
The functional API handles that case. Calling Enum(...) with a class name and a description of the members builds an enum class and returns it. You can also use it for quick throwaway enums in tests and scripts.
from enum import Enum
Animal = Enum("Animal", "ANT BEE CAT")
print(list(Animal)) # [<Animal.ANT: 1>, <Animal.BEE: 2>, <Animal.CAT: 3>]
print(Animal.BEE.value) # 2
print(Animal["CAT"]) # Animal.CAT
print(Animal(1)) # Animal.ANT
print(Animal) # <enum 'Animal'>The result behaves like an enum written with class. You get lookup by name and by value, iteration, identity comparison, and hashing.
How the call is interpreted
Enum is a class, so calling it normally means "look up a member by value", as in Color(2). The metaclass tells the two uses apart by the arguments.
The full signature has these parts that matter in practice:
value: the name of the new class. This first argument is a string.names: the members. Its accepted shapes are listed below.module: the module name stored in__module__.qualname: the qualified name stored in__qualname__.type: a mixin data type such asintorstr.start: the number given to the first auto-numbered member. The default is 1.
The accepted shapes of `names`
| Shape | Example | Resulting values |
|---|---|---|
| Space-separated string | `"ANT BEE CAT"` | Generated: 1, 2, 3 |
| Comma-separated string | `"ANT, BEE, CAT"` | Generated: 1, 2, 3 |
| Sequence of names | `["ANT", "BEE", "CAT"]` | Generated: 1, 2, 3 |
| Sequence of pairs | `[("OK", 200), ("NOT_FOUND", 404)]` | The values you give |
| Mapping | `{"OK": 200, "NOT_FOUND": 404}` | The values you give |
The first three shapes generate values. The last two give you full control over them.
from enum import Enum
Http = Enum("Http", [("OK", 200), ("NOT_FOUND", 404)])
HttpFromDict = Enum("HttpFromDict", {"OK": 200, "NOT_FOUND": 404})
print(Http.NOT_FOUND.value) # 404
print(HttpFromDict(200)) # HttpFromDict.OK
Names = Enum("Names", ["ALPHA", "BETA"])
print([m.value for m in Names]) # [1, 2]The usual enum rules still apply. If two names share a value, the later one becomes an alias of the first.
from enum import Enum
State = Enum("State", {"ACTIVE": 1, "ENABLED": 1, "DISABLED": 2})
print(State.ENABLED is State.ACTIVE) # True
print(len(list(State))) # 2
print(list(State.__members__)) # ['ACTIVE', 'ENABLED', 'DISABLED']Choosing the starting number
Generated values start at 1 because most people count that way. Pass start to change it.
from enum import Enum
Zero = Enum("Zero", "A B C", start=0)
print([m.value for m in Zero]) # [0, 1, 2]
Hundred = Enum("Hundred", "A B C", start=100)
print([m.value for m in Hundred]) # [100, 101, 102]start only affects generated values. It has no effect on the pair and mapping shapes, where you supply every value yourself.
A plain Enum member is always truthy, even when its value is 0. Integer-based enums are different, because they inherit truthiness from int. This comes up often after start=0:
from enum import Enum, IntEnum
Plain = Enum("Plain", "A B", start=0)
Counted = IntEnum("Counted", "A B", start=0)
print(bool(Plain.A)) # True
print(bool(Counted.A)) # FalseFunctional forms of IntEnum, StrEnum and Flag
Every enum base class can be called this way. The IntEnum, StrEnum and Flag variants generate values with their own rules, which are the same rules auto() follows in the class syntax.
from enum import Flag, IntEnum, StrEnum # StrEnum requires Python 3.11+
Level = IntEnum("Level", "LOW MEDIUM HIGH")
Mode = StrEnum("Mode", "READ WRITE")
Perm = Flag("Perm", "R W X")
print([m.value for m in Level]) # [1, 2, 3]
print([m.value for m in Mode]) # ['read', 'write']
print([m.value for m in Perm]) # [1, 2, 4]
print(Level.HIGH > Level.LOW) # True
print(Mode.READ == "read") # True
print(Perm.R | Perm.X) # Perm.R|XYou can also use the type argument to mix a data type into a plain Enum. This is how you get members that are also str or int without picking a specialized base class.
from enum import Enum
Mode = Enum("Mode", [("READ", "r"), ("WRITE", "w")], type=str)
print(Mode.READ == "r") # True
print(isinstance(Mode.READ, str)) # TrueBuilding an enum from runtime data
The strongest reason to use the functional API is that the member list can be computed. This example derives an enum from a list of workflow stage names, as if they had been read from a settings file.
from enum import Enum
config_names = ["draft", "review", "published"]
Stage = Enum(
"Stage",
{name.upper(): number for number, name in enumerate(config_names, start=1)},
module=__name__,
)
for stage in Stage:
print(stage.name, stage.value)
# DRAFT 1
# REVIEW 2
# PUBLISHED 3
print(Stage["REVIEW"] is Stage(2)) # TrueBecause the member names are built from data, a typo in the code can no longer be caught at the point where you write Stage.PUBLISHD. You will only find the error when that line runs. Keep this in mind before you replace a stable class definition with generated members.
Pickling and the `module` argument
Pickle stores an enum member as a reference: the module name, the class name, and the value. When it loads the data, it imports the module, finds the class by name, and calls it with the value. For this to work, the class must record the right module and be reachable under its own name in that module.
With the class syntax, Python fills in __module__ for you. With the functional API, it tries to find the module by inspecting the calling frame. That inspection can fail in some environments, and then the module is unknown and pickling fails. Passing module=__name__ removes the guesswork.
import pickle
from enum import Enum
Animal = Enum("Animal", "ANT BEE CAT", module=__name__)
data = pickle.dumps(Animal.BEE)
restored = pickle.loads(data)
print(restored is Animal.BEE) # TrueTwo further rules apply:
- The variable name and the class name string must match. If you write
Pet = Enum("Animal", ...), pickle looks forAnimalin the module and does not find it. - A class created inside a function is not importable by name, so its members cannot be pickled even with
moduleset. Define such enums at module level.
If the class lives somewhere other than where it is built, use qualname to give its dotted path, for example qualname="Config.Mode" for a class you assign to an attribute named Mode on a class named Config.
Adding methods to a functional enum
The functional API has no place to write a method. The usual workaround is a base enum that has methods but no members. Calling that base class with names creates a subclass that inherits the methods.
from enum import Enum
class Describable(Enum):
def describe(self):
return f"{self.name.lower()} ({self.value})"
Fruit = Describable("Fruit", "APPLE PEAR")
print(Fruit.PEAR.describe()) # pear (2)
print(issubclass(Fruit, Describable)) # TrueThis works because Python only forbids subclassing an enum that already has members. A base with no members can be extended freely, and the functional call is one way to extend it.
Limits and failure modes
- Static typing. Type checkers read your source code and do not run it. Most of them can follow a functional call only when its arguments are literal strings or literal collections. A dynamic call like the
Stageexample above gives the checker no member list, soStage.DRAFTmay be reported as an unknown attribute. If you need type checking, write a class. - Calling an enum that already has members.
Color("Shade", "LIGHT DARK")on a populated enum is an attempt to subclass it and raisesTypeError. Use a base class without members if you want a family of functional enums. - Invalid names. Names beginning and ending with a single underscore are reserved for the enum machinery and are rejected. Names that are not valid identifiers can be stored but cannot be reached with attribute syntax, so avoid them.
- Readability. A generated enum has no definition to read. Anyone searching the code for
PUBLISHEDwill find nothing, because the name only exists in the data.
Summary
- Calling
Enum("Name", names)builds a new enum class. Calling an existing enum with only a value looks up a member. namesaccepts a space or comma separated string, a sequence of names, a sequence of(name, value)pairs, or a mapping.- Generated values start at 1. Use
startto change this, and expect a falsy first member whenstart=0is combined with an integer base. IntEnum,StrEnumandFlagcan all be called this way, andtype=mixes a data type into a plainEnum.- Pass
module=__name__when pickling is needed, and make the variable name match the class name. - To give functional enums methods, call a member-less base enum class.
Exercise
Write code that builds an enum named Weekday from the list ["mon", "tue", "wed"]. The member names must be upper case, the values must be 1, 2 and 3, and the enum must be safe to pickle when this code runs at module level. Then print Weekday(2).
Show answer
from enum import Enum days = ["mon", "tue", "wed"] Weekday = Enum( "Weekday", {name.upper(): number for number, name in enumerate(days, start=1)}, module=_name_, ) print(Weekday(2)) # Weekday.TUE
Exercise
Given Level = IntEnum("Level", "LOW MEDIUM HIGH", start=0), what do bool(Level.LOW) and bool(Level.MEDIUM) print, and why? What would the first one print if Level were created with Enum instead of IntEnum?
Show answer
bool(Level.LOW) prints False and bool(Level.MEDIUM) prints True. With start=0, LOW has the value 0, and IntEnum members take their truthiness from int, so 0 is falsy. A plain Enum member is always truthy, so bool(Level.LOW) would print True.