Sub topic 7
Adding methods, properties and fields to members
An enum member is an ordinary Python object, so you can attach behavior and data to it. This chapter shows how to add methods, properties and extra fields, and which class-body lines Python turns into members. It assumes you can read class definitions, use @property and @classmethod, and know the difference between == and is. It also assumes you have seen Enum, .name, .value and value lookup such as Color(2) in earlier chapters.
Why attach behavior to members
Code that works with enum values often ends up with helper functions that start with if color is Color.RED. Moving that logic into the enum keeps it next to the values it describes. Callers write day.is_weekend() instead of importing a separate helper.
Python allows this because Enum is a class. Each member is a singleton instance of that class, and every method you define is available on every member.
Methods and class methods
Define methods as you would in any class. self is the member the method was called on.
from enum import Enum
class Weekday(Enum):
MON = 1
TUE = 2
WED = 3
THU = 4
FRI = 5
SAT = 6
SUN = 7
def is_weekend(self):
return self in (Weekday.SAT, Weekday.SUN)
def next(self):
members = list(type(self))
return members[(members.index(self) + 1) % len(members)]
@classmethod
def weekdays(cls):
return [day for day in cls if not day.is_weekend()]
print(Weekday.SAT.is_weekend()) # True
print(Weekday.SUN.next()) # Weekday.MON
print(Weekday.weekdays()) # [<Weekday.MON: 1>, ..., <Weekday.FRI: 5>]Three details matter here:
type(self)returns the enum class, sonextkeeps working if someone subclasses the enum (only possible when it has no members).- Iterating over the class skips aliases, so
nextnever lands on an alias. - A class method receives the enum class, which makes it a natural place for alternative lookups.
Properties
A @property computes a value from the member's data each time you read it. It works like a property on any other class.
from enum import Enum
G = 6.67300e-11
class Planet(Enum):
MERCURY = (3.303e+23, 2.4397e6)
EARTH = (5.976e+24, 6.37814e6)
def __init__(self, mass, radius):
self.mass = mass
self.radius = radius
@property
def surface_gravity(self):
return G * self.mass / (self.radius * self.radius)
print(round(Planet.EARTH.surface_gravity, 1)) # 9.8
print(Planet.EARTH.value) # (5.976e+24, 6378140.0)The G constant sits at module level on purpose. The next section explains why it cannot go inside the class.
Fields set in `__init__`
When a member's value is a tuple, Python unpacks it into the arguments of __init__. In Planet, EARTH = (5.976e+24, 6.37814e6) makes Python call __init__(member, 5.976e+24, 6.37814e6). The method stores the pieces as attributes.
Two facts follow from this:
.valuestill holds the whole original tuple. The unpacked fields are extra attributes, not replacements.- Value lookup uses the whole tuple. This surprises people, as the next example shows.
from enum import Enum
class HttpStatus(Enum):
OK = (200, "OK")
NOT_FOUND = (404, "Not Found")
def __init__(self, code, phrase):
self.code = code
self.phrase = phrase
def __str__(self):
return f"{self.code} {self.phrase}"
@classmethod
def from_code(cls, code):
for member in cls:
if member.code == code:
return member
raise ValueError(f"unknown status code: {code}")
print(HttpStatus.NOT_FOUND.code) # 404
print(HttpStatus.NOT_FOUND) # 404 Not Found
print(HttpStatus.from_code(200)) # 200 OK
try:
HttpStatus(404)
except ValueError as error:
print(error) # 404 is not a valid HttpStatusHttpStatus(404) fails because the stored value is (404, "Not Found"), not 404. The from_code class method is one fix. It scans every member, so it is linear in the number of members. For large enums, build a dictionary once.
Making a field the value with `__new__`
If you want .value to be just the code and want lookups like HttpStatus(404) to work, define __new__ instead of __init__. Inside __new__ you create the instance yourself and set _value_ explicitly.
from enum import Enum
class HttpStatus(Enum):
def __new__(cls, code, phrase):
member = object.__new__(cls)
member._value_ = code
member.phrase = phrase
return member
OK = (200, "OK")
NOT_FOUND = (404, "Not Found")
print(HttpStatus(404)) # HttpStatus.NOT_FOUND
print(HttpStatus.NOT_FOUND.value) # 404
print(HttpStatus.NOT_FOUND.phrase) # Not FoundUse object.__new__(cls), not cls(...), because calling the enum class would trigger a lookup and recurse. Here _value_ decides both what .value returns and which members count as aliases. Two members with the same _value_ become aliases even if their other fields differ.
The following table compares the two approaches.
| Approach | `.value` | `Enum(404)` lookup | Complexity |
|---|---|---|---|
| `__init__` with tuple values | The whole tuple | Needs the whole tuple | Low |
| `__new__` that sets `_value_` | The single chosen field | Works with that field | Higher |
What becomes a member and what does not
Python's enum machinery looks at each name assigned in the class body and decides whether it is a member. Functions, properties, class methods, static methods and other descriptors stay ordinary class attributes. Dunder names (__init__) and single-underscore names with trailing underscores (_value_) are also left alone. Almost everything else becomes a member.
This rule creates two common errors.
The second error affects callables used as values. A function is a descriptor, so it is not turned into a member.
from enum import Enum
class Broken(Enum):
DOUBLE = lambda x: x * 2
NEGATE = lambda x: -x
print(list(Broken)) # []The enum is empty. Both lambdas became ordinary methods. To store functions as member data, wrap each one in a tuple and take it in __init__:
from enum import Enum
class Op(Enum):
DOUBLE = (lambda x: x * 2,)
NEGATE = (lambda x: -x,)
def __init__(self, func):
self.func = func
def __call__(self, x):
return self.func(x)
print(Op.DOUBLE(21)) # 42
print(list(Op)) # [<Op.DOUBLE: (<function ...>,)>, <Op.NEGATE: (<function ...>,)>]A tuple is not a descriptor, so each line becomes a member. __call__ is defined on the class, which makes members callable.
Changing members after creation
Members are normal objects, so Planet.EARTH.mass = 1 does not raise an error. Do not do it. Each member is a singleton shared by the whole program, so a change made in one module is visible everywhere. Treat fields as read-only after __init__. If you need per-use state, keep it in a separate object that refers to the member.
Avoid giving fields the names name or value. Those names are used by the enum itself, and shadowing them leads to confusing errors.
Overriding `__str__` and `__repr__`
HttpStatus above overrides __str__ to print 404 Not Found. This is a common use of methods on enums. Keep __repr__ unchanged unless you have a reason. The default form, <HttpStatus.NOT_FOUND: (404, 'Not Found')>, shows the class, name and value, which helps when debugging. Override __str__ for user-facing text only.
Common errors in this area
- Constants inside the class body. They become members or cause a
TypeError. Move them to module level or usenonmember. - Callables as values. Plain functions and lambdas vanish from the member list. Wrap them in a tuple.
- Looking up by one field. With
__init__,Enum(value)needs the full tuple. Use a class method, a dictionary, or__new__with_value_. - Calling the enum class inside
__new__. Useobject.__new__(cls). - Mutating members. It works, but the change is global.
Exercise
A class Planet(Enum) defines MERCURY = (3.303e+23, 2.4397e6) and an __init__(self, mass, radius). What does Planet.MERCURY.value return, and what does Planet.MERCURY.mass return?
Show answer
Planet.MERCURY.value returns the whole tuple (3.303e+23, 2439700.0). Planet.MERCURY.mass returns 3.303e+23, because __init__ unpacked the tuple and stored the first item as the mass attribute.
Exercise
Write a Level(Enum) with members LOW, MEDIUM and HIGH whose .value is the integer 1, 2 or 3, and give each member a label field ("Low", "Medium", "High"). Make Level(2) return Level.MEDIUM.
Show answer
Use __new__ and set _value_:
class Level(Enum):
def _new(cls, number, label):
member = object.new(cls)
member.value = number
member.label = label
return member
LOW = (1, "Low")
MEDIUM = (2, "Medium")
HIGH = (3, "High")
With this definition Level(2) returns Level.MEDIUM and Level.MEDIUM.label is "Medium". A version that only uses `init_ would keep the tuple as the value, so Level(2) would raise ValueError`.