Sub topic 6
Comparing members: identity, equality and hashing
This chapter assumes you know the difference between == and is, and that you can define a basic Enum class. It covers how members compare, why plain enums refuse ordering, and what hashing means for dictionaries and sets.
Members are singletons
Python creates each member once, when the class body runs. Every lookup returns that same object, whether you use the attribute, the value, or the name.
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
print(Color.RED is Color(1)) # True
print(Color.RED is Color["RED"]) # True
print(Color.RED is Color.GREEN) # FalseBecause members are singletons, is is a reliable and cheap test. Aliases are not separate objects either. They are extra names for the same member. Copying and unpickling a member also gives back the original object, not a new one.
flowchart LREquality
Enum does not define a custom __eq__. Equality falls back to identity, so two members are equal only if they are the same member.
A member is also never equal to its raw value.
from enum import Enum
class Color(Enum):
RED = 1
print(Color.RED == Color.RED) # True
print(Color.RED == 1) # False
print(Color.RED.value == 1) # TrueCompare .value explicitly when you need to match against raw data such as a number read from a file. Better still, convert the raw data once with Color(1) and compare members from then on.
No ordering for plain Enum
Members of a plain Enum have no natural order, so the comparison operators <, >, <= and >= raise TypeError.
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
try:
Color.RED < Color.GREEN
except TypeError as exc:
print(exc)The output is '<' not supported between instances of 'Color' and 'Color'. This is deliberate. If your members have a real ordering, such as priorities, use IntEnum (covered in a later chapter) or compare their .value attributes.
Hashing
Members are hashable, so you can use them as dictionary keys and as set elements. This is one of the most common uses of enums.
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
hex_codes = {Color.RED: "#ff0000", Color.GREEN: "#00ff00"}
print(hex_codes[Color.RED]) # #ff0000
print(Color.GREEN in {Color.RED}) # FalseA dictionary keyed by enum members cannot be accidentally looked up with a raw value. hex_codes[1] raises KeyError, which helps catch mixed-up types.
When equality and hashing change: IntEnum
IntEnum members are also real int objects. They compare equal to integers, and they hash the same as the matching integer. As a result, they can find plain int keys in a dictionary.
from enum import IntEnum
class Priority(IntEnum):
LOW = 1
HIGH = 3
table = {1: "one", 3: "three"}
print(Priority.LOW == 1) # True
print(hash(Priority.LOW) == hash(1)) # True
print(table[Priority.HIGH]) # three
print(Priority.LOW < Priority.HIGH) # TrueThis is convenient, but it also removes the type safety that plain enums give you. Two unrelated IntEnum classes can compare equal if their values match.
from enum import IntEnum
class Size(IntEnum):
SMALL = 1
class Level(IntEnum):
LOW = 1
print(Size.SMALL == Level.LOW) # TrueSummary of behavior
| Operation | Plain `Enum` | `IntEnum` |
|---|---|---|
| `member is member` | Same object | Same object |
| `member == 1` | `False` | `True` if the value is 1 |
| `member < other` | `TypeError` | Works like `int` |
| Usable as dict key | Yes | Yes, and matches `int` keys |
Exercise
Given class Color(Enum): RED = 1 and class Level(IntEnum): LOW = 1, what do Color.RED == Level.LOW and {1: "x"}[Level.LOW] return?
Show answer
Color.RED == Level.LOW is False, because Color.RED is a plain Enum member that only equals itself. {1: "x"}[Level.LOW] returns "x", because Level.LOW equals 1 and hashes the same as 1.