Enums (the enum module)

Published by Brayan K

An enum is a class that bundles a fixed set of named constant values into one self-documenting type, so a variable can only ever hold one of the choices you defined.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

A status is a member, not its spelling

A delivery can be pending, sent or failed. Scattered strings let a typo such as "send" become another apparent status. An enum gives those choices one definition. The assignment in its class body creates a member with a name and a value; it does not make the member an ordinary string.

from enum import Enum

class Status(Enum):
    PENDING = "pending"
    SENT = "sent"
    FAILED = "failed"

# Keep the member inside the program; use its value at a text boundary.
current = Status.SENT
print(current)
print(current.name)
print(current.value)
print(current == "sent")
print(current is Status.SENT)

# ✅ Expected output:
# Status.SENT
# SENT
# sent
# False
# True

The member prints with its class and name. Its name is the identifier in the definition, while value is the text we chose to store. Compare a status with Status.SENT, not with its value. A spelling mismatch between a member and a raw string returns false; it does not raise an error.

The enum validates a value when you look up a member; it does not prevent an ordinary Python variable from being reassigned to unrelated data. Plain Enum models one named choice. Flag, introduced below, models a combination of named options.

Class and object mechanics belong to Object-Oriented Programming (OOP) in Python. Here the class declares a closed set of choices rather than a new object for every delivery.

Convert external text once, then use members

Status("sent") finds a member by value. Status["SENT"] finds one by name. Parentheses do not create a new status: both lookups return the existing member.

from enum import Enum

class Status(Enum):
    PENDING = "pending"
    SENT = "sent"
    FAILED = "failed"

from_value = Status("sent")
from_name = Status["SENT"]
print(from_value is from_name)
print(from_value.name)

# ✅ Expected output:
# True
# SENT
from enum import Enum

class Status(Enum):
    PENDING = "pending"
    SENT = "sent"
    FAILED = "failed"

Status("send")

# ✅ Expected error:
# ValueError: 'send' is not a valid Status

Repair the input or reject it at the boundary. Silently treating an unknown value as pending could hide a delivery failure. A name lookup uses the exact uppercase identifier here; Status["sent"] is a different request.

from enum import Enum

class Status(Enum):
    PENDING = "pending"
    SENT = "sent"
    FAILED = "failed"

Status["sent"]

# ✅ Expected error:
# KeyError: 'sent'

The independent exercise catches an invalid value and reports it separately. Exception Handling owns how try and except select a handler.

Duplicate values make aliases unless you forbid them

Two names with the same value normally identify one member. The first name is canonical. Iterating the enum yields canonical members in definition order; __members__ also contains alias names. This distinction matters when generating a menu or counting the choices.

from enum import Enum

class Colour(Enum):
    RED = "red"
    CRIMSON = "red"
    BLUE = "blue"

print(Colour.CRIMSON is Colour.RED)
print(Colour.CRIMSON.name)
print([member.name for member in Colour])
print(list(Colour.__members__))

# ✅ Expected output:
# True
# RED
# ['RED', 'BLUE']
# ['RED', 'CRIMSON', 'BLUE']

An alias can preserve an older name, but an accidental duplicate can hide a choice. Add @unique when every name must have its own value. Validation happens when Python finishes defining the class, before any instance is requested.

from enum import Enum, unique

@unique
class Priority(Enum):
    LOW = 1
    HIGH = 1

# ✅ Expected error:
# ValueError: duplicate values found in <enum 'Priority'>: HIGH -> LOW

Changing HIGH to a distinct value repairs this definition. Existing members cannot be reassigned after the class has been built:

from enum import Enum

class Status(Enum):
    PENDING = "pending"
    SENT = "sent"
    FAILED = "failed"

Status.SENT = "delivered"

# ✅ Expected error:
# AttributeError: cannot reassign member 'SENT'

Choose explicit values when another system stores them

auto() can supply integer values when only distinct members matter. For a plain Enum with only auto values, numbering starts at one and follows definition order. Inserting a new choice can change later numbers, so do not use those incidental numbers as stable database IDs or protocol codes.

from enum import Enum, auto

class Screen(Enum):
    HOME = auto()
    EDIT = auto()
    HELP = auto()

class Response(Enum):
    ACCEPTED = 202
    NOT_FOUND = 404

print([(item.name, item.value) for item in Screen])
print(Response.NOT_FOUND.value)

# ✅ Expected output:
# [('HOME', 1), ('EDIT', 2), ('HELP', 3)]
# 404

A stored value should have a deliberate migration story. Renaming a Python member while retaining its explicit value can preserve value-based data; changing the value cannot. For text serialization, send member.value and reconstruct it with the enum class when reading it.

IntEnum and StrEnum deliberately relax the boundary

A plain Enum does not compare equal to its raw integer or string value. IntEnum and StrEnum also behave as integers and strings, which helps when replacing existing constants, but permits comparisons that a plain Enum would reject. Arithmetic and string operations can produce ordinary values rather than enum members.

from enum import Enum, IntEnum, StrEnum

class StrictCode(Enum):
    OK = 200

class Code(IntEnum):
    OK = 200

class Mode(StrEnum):
    QUIET = "quiet"

print(StrictCode.OK == 200)
print(Code.OK == 200)
print(type(Code.OK + 1).__name__)
print(Mode.QUIET == "quiet")
print(type(Mode.QUIET.upper()).__name__)

# ✅ Expected output:
# False
# True
# int
# True
# str

Choose the relaxed type because an interface needs it, not merely because the values happen to be numbers or strings. StrEnum is available from Python 3.11. Some third-party code checks for exactly str rather than a subclass; pass str(member) at that boundary.

Enum members also work as qualified patterns such as case Status.SENT:. Structural Pattern Matching (match/case) owns matching rules and the difference between a qualified value and a capturing name.

Combine independent options with Flag

A delivery status is one choice, but a document can allow reading and writing at the same time. Plain Enum does not supply a union operation for its members. Integer values alone do not turn it into a set of options.

from enum import Enum

class Access(Enum):
    READ = 1
    WRITE = 2

print(Access.READ | Access.WRITE)

# ✅ Expected error:
# TypeError: unsupported operand type(s) for |: 'Access' and 'Access'

Use Flag for combinable options. Each independent flag needs its own bit: the values are powers of two. For Flag, auto() supplies those powers rather than the consecutive values used by plain Enum. A value of three combines the first two bits; it would not be a third independent permission.

from enum import Flag, auto

class Access(Flag):
    READ = auto()
    WRITE = auto()
    SHARE = auto()

allowed = Access.READ | Access.WRITE
print([(item.name, item.value) for item in Access])
print(allowed.name)
print(allowed.value)
print(Access.READ in allowed)
print(Access.SHARE in allowed)
print(Access(0).value, bool(Access(0)))



# ✅ Expected output:
# [('READ', 1), ('WRITE', 2), ('SHARE', 4)]
# READ|WRITE
# 3
# True
# False
# 0 False

The result of | is still an Access flag, even though READ | WRITE has no separate line in the class. Access(0) represents no enabled options and is false in a condition. Use | to combine flags and & to find their overlap; Python’s boolean or and and return operands instead of combining their bits.

from enum import Flag, auto

class Access(Flag):
    READ = auto()
    WRITE = auto()

print((Access.READ or Access.WRITE).name)
print((Access.READ | Access.WRITE).name)



# ✅ Expected output:
# READ
# READ|WRITE

Boolean short-circuiting belongs to Booleans & Truthiness. This lesson owns how named flags combine; defining your own operator methods belongs to Operator Overloading & Custom Behaviours.

Check all required options, then remove one safely

A nonzero overlap means at least one required option is present. It does not mean they are all present. Compare the overlap with the entire requirement, or use Flag membership. A zero requirement is contained in every combination; reject it separately if an empty requirement would be a configuration mistake in your application.

from enum import Flag, auto

class Access(Flag):
    READ = auto()
    WRITE = auto()
    SHARE = auto()

allowed = Access.READ | Access.SHARE
required = Access.READ | Access.WRITE
print(bool(allowed & required))
print((allowed & required) == required)
print(required in allowed)
print(Access(0) in allowed)



# ✅ Expected output:
# True
# False
# False
# True

For a Flag, ~ selects the named bits that are absent, within that flag type. It does not produce the negative integer you get from complementing an ordinary int. Use allowed & ~Access.WRITE to clear WRITE. Repeating that removal leaves it absent. By contrast, ^ toggles a bit, so repeating it can restore a permission you meant to remove.

from enum import Flag, auto

class Access(Flag):
    READ = auto()
    WRITE = auto()
    SHARE = auto()

allowed = Access.READ | Access.WRITE
print((~Access.WRITE).name)
allowed &= ~Access.WRITE
print(allowed.name)
allowed &= ~Access.WRITE
print(allowed.name)
print((allowed ^ Access.WRITE).name)



# ✅ Expected output:
# READ|SHARE
# READ
# READ
# READ|WRITE

Remove writing while retaining reading

Start with both READ and WRITE, then clear WRITE without toggling it back on. Fill the two expressions. Run the removal twice to check that a repeated request leaves the same permissions.

from enum import Flag, auto

class Access(Flag):
    READ = auto()
    WRITE = auto()

allowed = ___
keep = ___
allowed &= keep
print(allowed.name)
allowed &= keep
print(allowed.name)

# 👉 replace ___ with Access.READ | Access.WRITE
# 👉 replace ___ with ~Access.WRITE


# ✅ Expected output:
# READ
# READ

Use IntFlag only when integer interoperability is needed

IntFlag also behaves as an integer. Bitwise combinations can retain the flag type, but arithmetic such as addition produces an ordinary int. That difference can silently remove the named-option boundary. Prefer Flag for an internal model; choose IntFlag when an existing interface needs integer compatibility.

from enum import IntFlag, auto

class Access(IntFlag):
    READ = auto()
    WRITE = auto()

combined = Access.READ | Access.WRITE
added = Access.READ + Access.WRITE
print(type(combined).__name__, combined.value)
print(type(added).__name__, added)
print(Access.READ == 1)
print(Access(8).value)



# ✅ Expected output:
# Access 3
# int 3
# True
# 8

IntFlag keeps unknown bits by default, which is why constructing Access(8) above does not validate it against the named options. Flag rejects unknown bits by default. If an integer interface must reject them too, declare class Access(IntFlag, boundary=STRICT): after importing STRICT from enum. Do not treat a permissive conversion as permission validation. The Python flag-boundary reference documents these policies.

For flags stored outside the program, choose explicit stable bit values, just as status codes need explicit stable values. auto() is convenient for local definitions; inserting an option can change which bit later names receive.

Complete a delivery label

Convert the incoming value to a Status, then read its name and stored value. Each blank has its literal replacement beside it. The panel describes the completed program.

from enum import Enum

class Status(Enum):
    PENDING = "pending"
    SENT = "sent"
    FAILED = "failed"

current = ___("sent")
# 👉 replace ___ with Status
print(current.___)
# 👉 replace ___ with name
print(current.___)
# 👉 replace ___ with value

# ✅ Expected output:
# SENT
# sent

Count valid deliveries without inventing a status

Use the three-member Status definition to process ["sent", "pending", "send", "sent", "failed"]. Start every member count at zero. Convert each string by value, report rejected strings separately, then print each member name and count in definition order. Do not create an UNKNOWN member or silently change the bad input.

from enum import Enum

class Status(Enum):
    PENDING = "pending"
    SENT = "sent"
    FAILED = "failed"

counts = {member: 0 for member in Status}
rejected = []
for raw in ["sent", "pending", "send", "sent", "failed"]:
    try:
        member = Status(raw)
    except ValueError:
        rejected.append(raw)
    else:
        counts[member] += 1

for member in Status:
    print(member.name, counts[member])
print("rejected:", rejected)

# ✅ Expected output:
# PENDING 1
# SENT 2
# FAILED 1
# rejected: ['send']

Only conversion is inside the try block. A bug in the counting code should not be mistaken for an invalid external value. Enum members are dictionary keys here, so all later code works with the same validated choices.

Practice quiz

What does this program print? from enum import Enum class Status(Enum): PENDING = "pending" SENT = "sent" FAILED = "failed" print(Status.SENT == "sent")

  • True
  • False
  • sent
  • ValueError

Answer: False. A plain Enum member is distinct from its string value.

What does this program print? from enum import Enum class Status(Enum): PENDING = "pending" SENT = "sent" FAILED = "failed" print(Status("sent").name)

  • sent
  • Status
  • ValueError
  • SENT

Answer: SENT. Calling Status looks up a value and name reads the identifier.

What does this program print? from enum import Enum class Switch(Enum): ON = 1 YES = 1 print(Switch.YES is Switch.ON)

  • True
  • False
  • 1
  • TypeError

Answer: True. Equal values make YES an alias of the existing ON member.

What does this program print? from enum import Flag, auto class Access(Flag): READ = auto() WRITE = auto() SHARE = auto() allowed = Access.READ | Access.SHARE required = Access.READ | Access.WRITE print(bool(allowed & required)) print((allowed & required) == required)

  • False False
  • True True
  • True False
  • False True

Answer: True False. READ overlaps, but WRITE is missing. A truthy intersection proves only that some required bits are present.

What does this program print? from enum import IntEnum class Code(IntEnum): OK = 200 print(type(Code.OK + 1).__name__)

  • Code
  • int
  • IntEnum
  • str

Answer: int. Integer arithmetic returns an int, not a new Code member.

Access is a Flag with independent READ and WRITE bits. Starting from allowed = Access.READ | Access.WRITE, you execute allowed &= ~Access.WRITE twice. What does print(allowed.name) print?

  • WRITE
  • READ|WRITE
  • None
  • READ

Answer: READ. Clearing WRITE with an intersection removes it without toggling it back on; repeating the removal leaves READ.

An external service stores numeric status codes. Why use explicit values instead of auto()?

  • Inserting a member must not silently renumber the stored contract.
  • auto() is always random.
  • Explicit values make names case-insensitive.
  • auto() prevents iteration.

Answer: Inserting a member must not silently renumber the stored contract.. The storage contract needs stable chosen codes; automatic numbering follows the definition.

Which change catches duplicate enum values when the class is defined?

  • Compare the member to a string.
  • Call list() on the enum.
  • Decorate the class with @unique.
  • Rename the second member.

Answer: Decorate the class with @unique.. @unique rejects aliases caused by duplicate values; merely changing a name does not change the duplicate value.

Continue this course

Related lessons