Sub topic 6
Comparing members: identity, equality and hashing
This chapter explains how Python decides whether two enum members are the same, how == and is behave on them, and how members behave as dictionary keys and set elements. It assumes you can define an Enum class, you know the difference between == and is, and you know that a dictionary key must be hashable. A hashable object has a hash value that does not change and can be compared with ==.
Members are singletons
Each member of an enum exists exactly once per class. Python creates the members when the class body finishes running. Every later access (attribute access, lookup by value, lookup by name) returns that same object.
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
a = Color.RED
b = Color(1)
c = Color["RED"]
print(a is b) # True
print(b is c) # True
print(id(a) == id(c)) # TrueBecause members are singletons, is is a reliable and fast way to test for a member. The Python style guides and the standard library documentation both use is for this purpose:
def is_red(color: Color) -> bool:
return color is Color.REDAliases follow the same rule. An alias is a second name for an existing member, so it is the same object, not a copy.
from enum import Enum
class Status(Enum):
ACTIVE = 1
ENABLED = 1 # alias of ACTIVE
DISABLED = 2
print(Status.ENABLED is Status.ACTIVE) # True
print(Status(1) is Status.ENABLED) # TrueCopying and pickling also preserve identity. Enum classes define __reduce_ex__ and copy hooks so that the copy operations return the existing member.
import copy
import pickle
from enum import Enum
class Color(Enum):
RED = 1
print(copy.copy(Color.RED) is Color.RED) # True
print(copy.deepcopy(Color.RED) is Color.RED) # True
print(pickle.loads(pickle.dumps(Color.RED)) is Color.RED) # TrueThe pickle round trip works only when the class can be imported by name when loading. Define enums at module level, not inside functions, if you plan to pickle them.
Equality on plain Enum
A plain Enum does not define its own __eq__. It uses the default object behavior, which compares identity. This has three consequences.
- A member equals itself and nothing else.
- A member never equals its raw value.
- Members of two different enum classes are never equal, even if their values match.
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
class Shade(Enum):
RED = 1
print(Color.RED == Color.RED) # True
print(Color.RED != Color.GREEN) # True
print(Color.RED == 1) # False
print(Color.RED == Shade.RED) # False
print(Color.RED.value == Shade.RED.value) # TrueThe last line shows the way to compare values on purpose: read .value from both sides. Do this deliberately, because it throws away the type safety that made you choose an enum.
The refusal to equal a raw value is a feature. A function that receives 1 where it expected Color.RED should fail loudly, not quietly accept the wrong kind of object. The usual fix is to convert at the boundary: call Color(raw) when data enters your program, then work with members.
Ordering is not defined
Plain enums do not support <, <=, > or >=. Members have no natural order, even though their values might.
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
try:
Color.RED < Color.GREEN
except TypeError as exc:
print(exc) # '<' not supported between instances of 'Color' and 'Color'If you need ordering, you have two options. Use IntEnum (covered below), or sort with an explicit key such as sorted(members, key=lambda m: m.value). The explicit key makes the intent visible to the reader.
Hashing
Enum members are hashable, so you can use them as dictionary keys and set elements. This is one of the most common uses of enums, because the keys cannot be misspelled the way string keys can.
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
hex_codes = {
Color.RED: "#ff0000",
Color.GREEN: "#00ff00",
Color.BLUE: "#0000ff",
}
warm = {Color.RED}
print(hex_codes[Color.GREEN]) # #00ff00
print(Color.RED in warm) # True
print(Color.BLUE in warm) # FalseA dictionary lookup with a missing member raises KeyError, as with any dictionary. The same lookup with the raw value hex_codes[1] also raises KeyError, which follows from the equality rule above.
In CPython, Enum.__hash__ returns hash(self._name_). Treat that as an implementation detail. Two things follow from it:
- The hash of a member can differ from one run of the program to the next, because string hashes are randomized per process. Never store a member's hash in a file or compare hashes across processes.
- Two members of different classes with the same name can have the same hash. That is allowed. Dictionaries use
==to resolve collisions, and the members are not equal, so they stay separate keys.
Members whose values are unhashable, such as lists, are still hashable themselves, because the hash uses the name and not the value. Lookup by value (Color([1, 2])) falls back to a linear search in that case, which is slower but correct.
Mixins change equality and hashing
IntEnum and StrEnum inherit from int and str. Their __eq__, ordering methods and __hash__ come from the base type, so members behave like the raw value in comparisons. (StrEnum requires Python 3.11 or later.)
from enum import IntEnum, StrEnum
class Priority(IntEnum):
LOW = 1
HIGH = 3
class Size(IntEnum):
SMALL = 1
LARGE = 3
class Mode(StrEnum):
READ = "r"
WRITE = "w"
print(Priority.HIGH == 3) # True
print(Priority.LOW < Priority.HIGH) # True
print(Priority.LOW == Size.SMALL) # True
print(Mode.READ == "r") # True
print(hash(Priority.LOW) == hash(1)) # True
print(hash(Mode.READ) == hash("r")) # TrueThe line Priority.LOW == Size.SMALL prints True. Two unrelated enums compare equal because both are really the integer 1. This is the main reason to prefer plain Enum unless you need the integer or string behavior, for example to interoperate with an API, a database column or a file format.
Equal hashes plus equal values mean members and raw values collapse into one entry in dictionaries and sets:
from enum import IntEnum
class Priority(IntEnum):
LOW = 1
HIGH = 3
table = {1: "one"}
print(table[Priority.LOW]) # one
print(len({Priority.LOW, 1})) # 1Here is how the behaviors compare.
| Operation | Plain `Enum` | `IntEnum` / `StrEnum` |
|---|---|---|
| `member == raw_value` | `False` | `True` if the values match |
| `member_a < member_b` | `TypeError` | Works (`IntEnum`; `StrEnum` compares as strings) |
| Equal to a member of another class with the same value | `False` | `True` if the other is also an int or str enum |
| Hash equals the raw value's hash | No (based on name) | Yes |
| Looks up the same dictionary entry as the raw value | No | Yes |
How `==` is resolved
The diagram shows the decision Python makes when you write a == b with an enum member on the left.
Customizing equality safely
You can define __eq__ on an enum, but there is a trap. In Python, a class that defines __eq__ without __hash__ gets __hash__ = None, so its instances become unhashable. For an enum, that means the members can no longer be dictionary keys. Restore the hash explicitly.
from enum import Enum
class Level(Enum):
LOW = "low"
HIGH = "high"
def __eq__(self, other):
if isinstance(other, str):
return self.value == other.lower()
return NotImplemented
__hash__ = Enum.__hash__
print(Level.LOW == "LOW") # True
print(Level.LOW == Level.LOW) # True
print(Level.LOW == Level.HIGH) # False
print({Level.LOW: 1}[Level.LOW]) # 1Returning NotImplemented for other types lets Python fall back to the identity comparison, which keeps member-to-member equality correct.
This example still breaks the rule that equal objects must have equal hashes. Level.LOW == "low" is True, but hash(Level.LOW) is the hash of the name "LOW", which differs from hash("low"). A dictionary keyed by strings will not find Level.LOW. Custom equality like this is usually a sign that you want StrEnum, or that you should convert the string to a member once, with Level("low") or a _missing_ hook, and compare members afterward.
Flags compare by value
Flag members can be combined, and a combination is a new object. Combined members compare equal when they hold the same bits, so == is the right operator for flags. Do not rely on is for combinations.
from enum import Flag, auto
class Perm(Flag):
READ = auto()
WRITE = auto()
EXECUTE = auto()
print((Perm.READ | Perm.WRITE) == (Perm.WRITE | Perm.READ)) # True
print(Perm.READ == Perm.WRITE) # FalseGuidelines
- Use
isto test for a specific member, and==where it reads better or where combined flags are involved. - Convert raw data to members once at the boundary, then compare members with members.
- Choose plain
Enumwhen you want strict, type-safe comparisons. ChooseIntEnumorStrEnumonly when you need the member to act as an int or str outside Python. - Do not store or compare
hash()values of members across runs. - If you define
__eq__, define__hash__too.
Exercise
Given class Priority(IntEnum): LOW = 1; HIGH = 3 and class Color(Enum): RED = 1, what do Priority.LOW == 1, Color.RED == 1, and len({Priority.LOW, 1}) evaluate to, and why?
Show answer
Priority.LOW == 1 is True because IntEnum uses int equality. Color.RED == 1 is False because a plain Enum compares by identity and the integer is a different object. len({Priority.LOW, 1}) is 1 because the IntEnum member has the same hash and compares equal to 1, so the set keeps only one element.
Exercise
You add __eq__ to an enum class so that members compare equal to strings, and now {Level.LOW: 1} raises TypeError: unhashable type. What happened, and what is the fix?
Show answer
Defining __eq__ in a class body without __hash__ sets __hash__ to None, which makes the members unhashable. The fix is to add __hash__ = Enum.__hash__ to the class body. Be aware that this still does not make hash(Level.LOW) match hash("low"), so a better design is StrEnum or converting strings to members at the boundary.