The internet abounds with implementations of enumerations for Python, but I thought it might be fun to take a crack at making one. My goals were:
- Immutability: users shouldn’t be able to modify the value at runtime
- Simplicity of definition: They should be easy to define
- Uniqueness: Two enum values aren’t equal unless they are the same, no matter what their numeric value is
- Iteration: The user can iterate over the values in the enum
- Pickle-able: Naturally…
It uses a metaclass to add a custom __setattr__, __getattr__, and __iter__ to the user’s “enum class”, and it looks like this:
import enum class Level(metaclass=enum.Enum): LOW=1 MEDIUM=2 HIGH=3 x = Level.LOW Level.HIGH = 19 # Throws an AttributeError etc...