Python Enums are evil
18 May 2024
The short answer is that enums derive their unique value by restricting a variable’s values in a program. This is contradictory to Python’s type system. Thus, Python enums are an elephant’s tusks.
In my practical life, there are two situations where I have felt a need for an Enum in Python.
- I might want to restrict the possible values of a column. An enum is useless here because it is not a valid dtype. You are encouraged to use a
pandas.Categorical
to achieve this. That’s not the same as an enum, becausenp.nan
is intrinsically supported as a valid value. - I want to restrict the values of a function argument. There are no ways for the interpreter to do this, but static type checkers do this. But why would I instead not use
typing.Literal
for this purpose?
I have found it convenient to define a Literal type that can be re-used across my codebase.
from typing import Literal
Fruit = Literal['apple', 'orange']
See Also
- Enums with SqlAlchemy
- Behaviour quirk of
Enum
andIntEnum
>>> from enum import Enum, IntEnum
>>> class Fruit(IntEnum):
... Apple = 1
... Orange = 2
...
>>> fruit = Fruit.Apple
>>> fruit == 1
True
>>> class Fruit(Enum):
... Apple = 1
... Orange = 2
...
>>> fruit = Fruit.Apple
>>> fruit == 1
False
Thus, even if you must, use an IntEnum
.