Python enum
last modified November 19, 2026 Python 3.15
In this article we show how to work with enumerations in Python.
An enumeration is a set of symbolic names bound to unique, constant values.
Enumerations describe a fixed set of choices, such as seasons, days of the
week, order states, or file permissions. Using
Season.WINTER instead of the number 4 or the string
'winter' makes the code readable, and a typo in a member name
fails immediately with an AttributeError.
Enumerations are created with the enum module, either with the
class keyword or with a functional API. The module also provides
the derived types IntEnum, StrEnum,
Flag, and IntFlag. By convention, enumeration names
are singular and member names are uppercase.
Creating an enumeration
An enumeration is a class that inherits from enum.Enum. Its
class attributes become the members.
#!/usr/bin/python
from enum import Enum
class Season(Enum):
SPRING = 1
SUMMER = 2
AUTUMN = 3
WINTER = 4
season = Season.SPRING
print(season)
if season == Season.SPRING:
print('Spring is here')
print(list(Season))
The Season enumeration has four members. We access a member
with the enumeration name, a dot, and the member name, and compare it with
==. Printing a member shows its qualified name;
list returns all members in definition order.
$ python season.py Season.SPRING Spring is here [<Season.SPRING: 1>, <Season.SUMMER: 2>, <Season.AUTUMN: 3>, <Season.WINTER: 4>]
Names and values
Each member has a name and a value. A member can
be looked up by its value or by its name.
#!/usr/bin/python
from enum import Enum
class Season(Enum):
SPRING = 1
SUMMER = 2
AUTUMN = 3
WINTER = 4
season = Season.SUMMER
print(season.name, season.value)
print(repr(season))
print(type(season), isinstance(season, Season))
print(Season(3))
print(Season['WINTER'])
print(2 in Season, Season.SPRING in Season)
try:
Season(7)
except ValueError as e:
print('error:', e)
The repr of a member shows both the name and the value. Every
member is an instance of its enumeration. Calling the enumeration with a
value, Season(3), returns the member with that value; indexing
with a name, Season['WINTER'], returns the member with that
name. Since Python 3.12 the in operator accepts values as well
as members. An unknown value raises ValueError; an unknown name
would raise KeyError.
$ python members.py SUMMER 2 <Season.SUMMER: 2> <enum 'Season'> True Season.AUTUMN Season.WINTER True True error: 7 is not a valid Season
Iteration
An enumeration is iterable and has a length.
#!/usr/bin/python
from enum import Enum
class Color(Enum):
RED = 'ff0000'
GREEN = '00ff00'
BLUE = '0000ff'
print(len(Color))
for color in Color:
print(f'{color.name:6} #{color.value}')
names = [c.name.lower() for c in Color]
print(names)
print(Color.RED in Color, 'RED' in Color.__members__)
The values do not have to be integers; here they are hex color codes.
Iteration yields the members in definition order. The
__members__ attribute is a read-only mapping from names to
members, which we use to check whether a name exists.
$ python iteration.py 3 RED #ff0000 GREEN #00ff00 BLUE #0000ff ['red', 'green', 'blue'] True True
Comparison and identity
Members are singletons: each member exists only once, and it cannot be changed.
#!/usr/bin/python
from enum import Enum
class Season(Enum):
SPRING = 1
SUMMER = 2
print(Season.SPRING is Season(1))
print(Season.SPRING == Season.SPRING, Season.SPRING != Season.SUMMER)
print(Season.SPRING == 1)
try:
Season.SPRING < Season.SUMMER
except TypeError as e:
print('error:', e)
try:
Season.SPRING = 5
except AttributeError as e:
print('error:', e)
seasons = {Season.SPRING: 'mild', Season.SUMMER: 'hot'}
print(seasons[Season(2)])
Because members are singletons, they can be compared with is as
well as ==. A member is not equal to its value:
Season.SPRING == 1 is false. Plain enumerations do not support
ordering, so < raises TypeError, and assigning
to a member raises AttributeError. Members are hashable and work
well as dictionary keys.
$ python compare.py True True True False error: '<' not supported between instances of 'Season' and 'Season' error: cannot reassign member 'SPRING' hot
Automatic values
When the actual values do not matter, the auto function
generates them.
#!/usr/bin/python
from enum import Enum, auto
class Season(Enum):
SPRING = auto()
SUMMER = auto()
AUTUMN = auto()
WINTER = auto()
class Method(Enum):
@staticmethod
def _generate_next_value_(name, start, count, last_values):
return name.lower()
GET = auto()
POST = auto()
DELETE = auto()
print([s.value for s in Season])
print([m.value for m in Method])
print(Method('post'))
In a plain Enum, auto produces 1, 2, 3, and so on.
Defining the _generate_next_value_ method changes this; it
receives the member name and must come before the members. Here each
value is the lowercase member name, so Method('post') finds the
POST member.
$ python auto_values.py [1, 2, 3, 4] ['get', 'post', 'delete'] Method.POST
Aliases and unique values
Two members can have the same value. The second one then becomes an alias of the first.
#!/usr/bin/python
from enum import Enum, unique
class Status(Enum):
ACTIVE = 1
INACTIVE = 2
ENABLED = 1
print(Status.ENABLED, Status.ENABLED is Status.ACTIVE)
print(list(Status))
print(list(Status.__members__))
try:
@unique
class Grade(Enum):
A = 1
B = 2
EXCELLENT = 1
except ValueError as e:
print('error:', e)
Status.ENABLED is the same object as Status.ACTIVE.
Aliases are not included in iteration, but they appear in
__members__. If duplicate values are a mistake, the
@unique decorator turns them into a ValueError when
the class is created.
$ python aliases.py Status.ACTIVE True [<Status.ACTIVE: 1>, <Status.INACTIVE: 2>] ['ACTIVE', 'INACTIVE', 'ENABLED'] error: duplicate values found in <enum 'Grade'>: EXCELLENT -> A
Functional API
Enumerations can also be created by calling Enum with a name and
a list of members.
#!/usr/bin/python
from enum import Enum
Season = Enum('Season', 'SPRING SUMMER AUTUMN WINTER')
print(list(Season))
Weekend = Enum('Weekend', ['SATURDAY', 'SUNDAY'], start=6)
print(list(Weekend))
Size = Enum('Size', [('SMALL', 's'), ('MEDIUM', 'm'), ('LARGE', 'l')])
print(Size('m'))
codes = {'OK': 200, 'NOT_FOUND': 404}
HttpStatus = Enum('HttpStatus', codes)
print(HttpStatus(404), HttpStatus.OK.value)
The members can be given as a string of names separated by spaces, a list of
names, a list of name-value pairs, or a mapping. With names only, the values
are counted from 1, or from start. The functional API is useful
when the members come from data, as with the codes dictionary.
$ python functional.py [<Season.SPRING: 1>, <Season.SUMMER: 2>, <Season.AUTUMN: 3>, <Season.WINTER: 4>] [<Weekend.SATURDAY: 6>, <Weekend.SUNDAY: 7>] Size.MEDIUM HttpStatus.NOT_FOUND 200
Methods and properties
An enumeration is a class, so it can have methods, properties, and class
methods. A tuple value can be unpacked into attributes in
__init__.
#!/usr/bin/python
from enum import Enum
G = 6.674e-11
class Planet(Enum):
MERCURY = (3.303e23, 2.4397e6)
EARTH = (5.976e24, 6.37814e6)
JUPITER = (1.9e27, 7.1492e7)
def __init__(self, mass, radius):
self.mass = mass
self.radius = radius
@property
def gravity(self):
return G * self.mass / self.radius ** 2
def weight(self, kg):
return kg * self.gravity
@classmethod
def heaviest(cls):
return max(cls, key=lambda p: p.mass)
for planet in Planet:
print(f'{planet.name:8} g={planet.gravity:5.2f} 70 kg weighs {planet.weight(70):7.1f} N')
print(Planet.EARTH.value)
print(Planet.heaviest())
Each planet's value is a tuple of its mass and radius; __init__
receives the tuple items as arguments. The gravity property and
the weight method compute physical quantities for each member,
and the heaviest class method searches all members.
$ python planets.py MERCURY g= 3.70 70 kg weighs 259.3 N EARTH g= 9.80 70 kg weighs 686.3 N JUPITER g=24.81 70 kg weighs 1736.7 N (5.976e+24, 6378140.0) Planet.JUPITER
IntEnum and StrEnum
The members of IntEnum and StrEnum are also
integers and strings. They can be used wherever an int or a
str is expected.
#!/usr/bin/python
import json
from enum import Enum, IntEnum, StrEnum
class Priority(IntEnum):
LOW = 1
MEDIUM = 2
HIGH = 3
class Mode(StrEnum):
READ = 'r'
WRITE = 'w'
print(Priority.HIGH > Priority.LOW, Priority.MEDIUM == 2)
print(sorted([Priority.HIGH, Priority.LOW]), Priority.HIGH + 1)
print(Mode.READ == 'r', Mode.WRITE.upper(), f'mode={Mode.WRITE}')
print(json.dumps({'priority': Priority.HIGH, 'mode': Mode.READ}))
class Color(Enum):
RED = 1
try:
json.dumps(Color.RED)
except TypeError as e:
print('error:', e)
IntEnum members can be ordered and compared with integers, and
arithmetic returns plain integers. StrEnum (Python 3.11) members
are equal to their string values and have all string methods; in an f-string
they print as the value. Both kinds serialize to JSON as their values, while
a plain Enum member raises TypeError. The loss of
type safety is the price: Priority.MEDIUM == 2 is true. Use the
mixed types when interoperability with existing integers or strings matters;
see Python f-string for how they format.
$ python int_str.py
True True
[<Priority.LOW: 1>, <Priority.HIGH: 3>] 4
True W mode=w
{"priority": 3, "mode": "r"}
error: Object of type Color is not JSON serializable
Flag
A Flag enumeration has members that can be combined with the
bitwise operators. With auto, the values are powers of two.
#!/usr/bin/python
from enum import Flag, auto
class Perm(Flag):
READ = auto()
WRITE = auto()
EXECUTE = auto()
ALL = READ | WRITE | EXECUTE
print(list(Perm))
print(Perm.READ.value, Perm.WRITE.value, Perm.EXECUTE.value)
perm = Perm.READ | Perm.WRITE
print(perm, perm.value)
print(Perm.WRITE in perm, Perm.EXECUTE in perm)
print(list(perm))
perm |= Perm.EXECUTE
print(perm, perm is Perm.ALL)
print(Perm.ALL & ~Perm.WRITE)
empty = Perm(0)
print(empty, bool(empty), bool(perm))
The | operator combines flags and in tests whether
a flag is set. Iterating over a combined value yields its single flags; the
multi-bit ALL member is an alias for the combination and is not
listed. ~ inverts a flag within the defined bits, so
Perm.ALL & ~Perm.WRITE removes the write permission. The
empty flag is false in a boolean context. IntFlag works the same
way and its members are also integers.
$ python flags.py [<Perm.READ: 1>, <Perm.WRITE: 2>, <Perm.EXECUTE: 4>] 1 2 4 Perm.READ|WRITE 3 True False [<Perm.READ: 1>, <Perm.WRITE: 2>] Perm.ALL True Perm.READ|EXECUTE Perm(0) False True
Pattern matching
Members are matched in a match statement with value patterns,
which are dotted names.
#!/usr/bin/python
from enum import Enum
class Day(Enum):
MONDAY = 1
TUESDAY = 2
WEDNESDAY = 3
THURSDAY = 4
FRIDAY = 5
SATURDAY = 6
SUNDAY = 7
def describe(day):
match day:
case Day.SATURDAY | Day.SUNDAY:
return 'weekend'
case Day.FRIDAY:
return 'almost weekend'
case Day():
return 'workday'
case _:
return 'not a day'
for day in [Day.MONDAY, Day.FRIDAY, Day.SUNDAY, 6]:
print(day, '->', describe(day))
The | combines alternatives into one case. The class pattern
Day() matches any member of Day, and the wildcard
_ catches everything else, such as the plain integer 6. More on
patterns is in Python pattern match.
$ python matching.py Day.MONDAY -> workday Day.FRIDAY -> almost weekend Day.SUNDAY -> weekend 6 -> not a day
Custom lookup with _missing_
When a value lookup fails, the enumeration calls the _missing_
class method. We can use it to accept other spellings of a value.
#!/usr/bin/python
from enum import Enum
class Currency(Enum):
EUR = 'EUR'
USD = 'USD'
CZK = 'CZK'
@classmethod
def _missing_(cls, value):
if isinstance(value, str):
for member in cls:
if member.value == value.strip().upper():
return member
return None
print(Currency('EUR'))
print(Currency(' usd '))
try:
Currency('GBP')
except ValueError as e:
print('error:', e)
Our _missing_ strips and uppercases strings and searches the
members again. Returning None means that nothing was found, and
the usual ValueError is raised. This is useful for parsing user
input or data files.
$ python lookup.py Currency.EUR Currency.USD error: 'GBP' is not a valid Currency
A state machine
In the last example we use an enumeration for the states of an order and a dictionary of allowed transitions.
#!/usr/bin/python
from enum import Enum, auto
class Status(Enum):
NEW = auto()
PAID = auto()
SHIPPED = auto()
DELIVERED = auto()
CANCELLED = auto()
def can_move_to(self, other):
return other in TRANSITIONS[self]
TRANSITIONS = {
Status.NEW: {Status.PAID, Status.CANCELLED},
Status.PAID: {Status.SHIPPED, Status.CANCELLED},
Status.SHIPPED: {Status.DELIVERED},
Status.DELIVERED: set(),
Status.CANCELLED: set(),
}
class Order:
def __init__(self, number):
self.number = number
self.status = Status.NEW
def move(self, new_status):
if not self.status.can_move_to(new_status):
raise ValueError(f'order {self.number}: '
f'{self.status.name} -> {new_status.name} not allowed')
print(f'order {self.number}: {self.status.name} -> {new_status.name}')
self.status = new_status
order = Order(1001)
for step in ['PAID', 'SHIPPED', 'CANCELLED', 'DELIVERED']:
try:
order.move(Status[step])
except ValueError as e:
print('error:', e)
print('final:', order.status)
Members are hashable, so they serve as dictionary keys and set items in
TRANSITIONS. The can_move_to method looks up the
allowed next states; the dictionary is defined after the class because it
refers to the members. Steps come in as strings and are converted with
Status[step]. Cancelling a shipped order is rejected, and the
order continues to DELIVERED.
$ python orders.py order 1001: NEW -> PAID order 1001: PAID -> SHIPPED error: order 1001: SHIPPED -> CANCELLED not allowed order 1001: SHIPPED -> DELIVERED final: Status.DELIVERED
Source
Enum HOWTO – Python documentation
In this article we have worked with enumerations in Python. See also Python pattern match, Python dataclass, and Python sentinel builtin.
Author
List all Python tutorials.