1. Home
  2. Blog
  3. Software Development

Software Development

Python Enum Explained: auto, IntEnum, StrEnum, Flag and Best Practices

A Python enum gives a fixed set of named values a proper type, so typos fail loudly and code reads clearly. Learn how to define and look up members, when to use auto, IntEnum, StrEnum and Flag, aliases and the unique decorator, members with extra data, JSON, match statements and the traps that catch people, all tested.

9 min read
Python enum explained: auto, IntEnum, StrEnum, Flag and best practices

Key takeaways

  • A Python enum defines a closed set of named constants: Status.PAID instead of the bare string "paid".
  • Plain Enum members are not equal to their values: Status.PAID == "paid" is False. IntEnum and StrEnum change that.
  • Status("shipped") looks up by value and raises ValueError for unknown values, which makes validation free.
  • json.dumps fails on plain enum members; serialise .value or use StrEnum.

Order statuses, user roles, priority levels, payment methods: every codebase has small sets of allowed values. Storing them as plain strings or numbers works until someone types "shiped", compares against "Paid", or passes 4 where only 1 to 3 make sense. A Python enum turns those loose constants into a real type that your editor can autocomplete, your type checker can verify and your code can validate in one line.

All examples ran on Python 3.13.6 and the output is shown as printed. StrEnum needs Python 3.11 or newer; everything else works from 3.6 onwards. For related modelling tools, see our Python dataclasses guide.

Why use an enum instead of strings?

  • Typos fail immediately: Status.SHIPED raises AttributeError, while "shiped" silently never matches.
  • One source of truth: the set of allowed values lives in one class, so listing them for a dropdown or validating input is trivial.
  • Readable and searchable: if order.status is Status.REFUNDED says exactly what it means, and you can find every use with a search.
  • Tooling: editors autocomplete members, and type hints like def ship(s: Status) let checkers catch wrong arguments.

Defining an enum

from enum import Enum

class Status(Enum):
    PENDING = "pending"
    PAID = "paid"
    SHIPPED = "shipped"
    REFUNDED = "refunded"

print(Status.PAID)           # Status.PAID
print(repr(Status.PAID))     # <Status.PAID: 'paid'>
print(Status.PAID.name)      # PAID
print(Status.PAID.value)     # paid

Each member has a name (the identifier) and a value (what you assigned). By convention names are uppercase, because members are constants. Members are created once, when the class is defined, and they are singletons: there is exactly one Status.PAID object in the program.

Looking up and listing members

Status("shipped")           # Status.SHIPPED   (by value)
Status["REFUNDED"]          # Status.REFUNDED  (by name)
[s.name for s in Status]    # ['PENDING', 'PAID', 'SHIPPED', 'REFUNDED']
len(Status)                 # 4

Status("lost")
# ValueError: 'lost' is not a valid Status

Calling the class with a value converts raw input, such as a string from a form or an API, into a member, and invalid values raise ValueError straight away. That one line replaces a hand-written if value not in ALLOWED check. Iteration follows definition order, so building a list of choices for a UI is a one-liner.

Comparison rules: identity, not strings

Status.PAID is Status("paid")   # True
Status.PAID == "paid"           # False

Status.PAID = "x"
# AttributeError: cannot reassign member 'PAID'

Because members are singletons, compare them with is (or ==, which works the same here). The surprise for many developers is the second line: a plain Enum member never equals its raw value. That is deliberate, it prevents accidental mixing of types, but it means code like if order.status == "paid" silently becomes always False after you switch to enums. Members are also read-only, so nobody can change Status.PAID at runtime.

auto(): let Python pick the values

from enum import auto

class Step(Enum):
    DRAFT = auto()
    REVIEW = auto()
    DONE = auto()

[(s.name, s.value) for s in Step]
# [('DRAFT', 1), ('REVIEW', 2), ('DONE', 3)]

When the values do not matter, only the names, auto() assigns them for you, starting at 1. Avoid it when values are stored in a database or sent over an API, because inserting a new member in the middle would renumber the ones after it and silently change their stored meaning.

IntEnum: members that behave like integers

from enum import IntEnum

class Priority(IntEnum):
    LOW = 1
    MEDIUM = 2
    HIGH = 3

Priority.HIGH > Priority.LOW            # True
Priority.HIGH == 3                       # True
sorted([Priority.HIGH, Priority.LOW])    # [<Priority.LOW: 1>, <Priority.HIGH: 3>]

IntEnum members are real integers, so they compare and sort numerically and equal their values. Use it for ordered levels, HTTP-like codes or values that must interoperate with code expecting ints. The trade-off is weaker type safety: Priority.HIGH + 1 is 4, and any integer comparison works, so mix-ups are not caught.

StrEnum: members that behave like strings

from enum import StrEnum

class Color(StrEnum):
    RED = auto()
    GREEN = auto()

print(Color.RED)            # red
Color.RED == "red"          # True
Color.RED.upper()           # 'RED'

In a StrEnum, auto() produces the lowercase member name, and members are genuine strings: they compare equal to text, support string methods and print as their value. This is the most convenient choice for values that travel as text, such as JSON fields, query parameters and database columns.

Flag: combinable options

from enum import Flag

class Perm(Flag):
    READ = auto()
    WRITE = auto()
    DELETE = auto()

rw = Perm.READ | Perm.WRITE
print(rw)                     # Perm.READ|WRITE
Perm.WRITE in rw              # True
Perm.DELETE in rw             # False
[p.name for p in rw]          # ['READ', 'WRITE']

A Flag enum gives each member a separate bit, so members combine with | into sets of options and you test membership with in. It suits permissions, feature toggles and file modes, and it stores compactly as a single integer.

Aliases and the unique decorator

class Alias(Enum):
    ACTIVE = 1
    ENABLED = 1

Alias.ENABLED                      # Alias.ACTIVE
Alias.ENABLED is Alias.ACTIVE      # True
list(Alias)                        # [<Alias.ACTIVE: 1>]

from enum import unique
@unique
class Bad(Enum):
    A = 1
    B = 1
# ValueError: duplicate values found in <enum 'Bad'>: B -> A

Two names with the same value make the second an alias of the first: it is the same member, and iteration skips it. Aliases are handy for renaming a member while keeping the old name working. When duplicates would be a bug, add @unique and Python refuses to create the class.

Members with extra data and methods

class Plan(Enum):
    FREE = (0, 1)
    PRO = (12, 10)

    def __init__(self, price, seats):
        self.price, self.seats = price, seats

    @property
    def per_seat(self):
        return self.price / self.seats

Plan.PRO.price, Plan.PRO.seats, Plan.PRO.per_seat   # (12, 10, 1.2)

Enums are classes, so members can carry several attributes and expose methods and properties. Keeping a plan’s price and seat count next to its name avoids parallel dictionaries that drift out of sync. Keep this to small, fixed data; anything that changes often belongs in a database. See our classes and objects guide for the class mechanics.

Tip: add a classmethod such as from_label to map messy external input (different spellings or cases) onto members in one tested place.

Enums with JSON and databases

json.dumps({"status": Status.PAID})
# TypeError: Object of type Status is not JSON serializable

json.dumps({"status": Status.PAID.value})   # '{"status": "paid"}'
json.dumps({"c": Color.RED})                # '{"c": "red"}'   (StrEnum works)

The standard json module does not know plain enums. Serialise .value when writing and convert back with Status(value) when reading, or use StrEnum or IntEnum, which serialise as their underlying type automatically. The same pattern applies to databases: store the value (a short string is clearest), and enforce it with a CHECK constraint so bad data cannot sneak in from other writers; see SQL constraints. Our Python JSON guide shows custom encoders if you prefer to handle enums globally.

Enums with match statements

def ship(s: Status):
    match s:
        case Status.PAID:
            return "ship it"
        case Status.PENDING:
            return "wait"
        case _:
            return "no action"

ship(Status.PAID), ship(Status.REFUNDED)   # ('ship it', 'no action')

Dotted names like Status.PAID in a case are value patterns, compared by equality, so enums read naturally in pattern matching. Type checkers such as mypy can even warn when a match over an enum misses a member, if you replace the catch-all with explicit cases.

Which enum type should you use?

Need Use
Strict, type-safe constants Enum
Values travel as text (JSON, APIs, DB) StrEnum
Ordered levels or numeric codes IntEnum
Combinable options Flag
Values do not matter Enum with auto()

Common enum mistakes

  • Comparing a plain Enum member with a string and getting False.
  • Using auto() for values that are persisted, then inserting a member in the middle.
  • Calling json.dumps on members without converting them.
  • Accidental duplicate values creating aliases; use @unique.
  • Using enums for data that changes at runtime, such as a product catalogue.
  • Mixing Status.PAID.name and .value: store values, display names or labels.

Final thoughts

A Python enum is a small investment that removes a whole class of bugs. Define allowed values once, convert raw input with Status(value), compare members by identity, and pick StrEnum, IntEnum or Flag when you need text, ordering or combinations. Store values, not names, and keep enums for genuinely fixed sets. For lookups keyed by enum members, our Python dictionary guide is a good companion.

Frequently asked questions

What is an enum in Python?

An enum is a class whose members are a fixed set of named constants, created with the enum module. Each member has a name and a value and is a singleton.

How do I get an enum member from its value?

Call the enum class with the value, for example Status with the string paid. It returns the matching member or raises ValueError if no member has that value.

Why is my enum member not equal to its value?

Plain Enum members are deliberately not equal to their raw values. Compare with the member itself, use .value, or switch to IntEnum or StrEnum, whose members equal their values.

What does auto do in a Python enum?

auto assigns values automatically. In a normal Enum it counts from 1, and in a StrEnum it uses the lowercase member name. Avoid it for values you store or send over an API.

How do I convert an enum to JSON?

Serialise the member value, such as Status.PAID.value, and rebuild the member with Status(value) when reading. StrEnum and IntEnum members serialise directly as strings and numbers.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Random Forest in Python: Bagging, Feature Sampling and OOB From Scratch

Random forest in Python from scratch: bootstrap sampling, feature sampling, number of trees, out-of-bag evaluation and impurity vs permutation importance.

Read article →
Software Development

MIME Types Explained: Content-Type, nosniff and a Common Types List

MIME types explained and tested in a browser: Content-Type, nosniff, scripts and stylesheets with wrong types, a common MIME types…

Read article →
DevOps

Git Clean Explained: Remove Untracked Files Without Regret

Git clean explained with dry runs: -n, -f, -d, -x, -X, exclusions, paths, nested repositories and interactive mode, plus a…

Read article →
Test Automation

Pytest approx: Comparing Floats With rel, abs and Collections

Pytest approx explained: default tolerances, the near-zero trap, rel and abs, lists and dicts, NaN, NumPy, and how it differs…

Read article →
Software Testing

Accessibility Testing: WCAG Checklist, Automated Tools and Manual Checks

Accessibility testing explained: WCAG basics, an axe-core scan of a broken and a fixed page, what automation missed, contrast checks…

Read article →
Databases & SQL

SQL UNPIVOT: Turn Columns Into Rows, 4 Ways Tested

SQL UNPIVOT explained: turn columns into rows with UNION ALL, CROSS JOIN with CASE, JSON functions or native UNPIVOT, with…

Read article →
Software Development

Intl NumberFormat in JavaScript: Currency, Compact, Percent and Units

Intl.NumberFormat in JavaScript: locales, currency, compact notation, percent, units, rounding, formatToParts, the non-breaking space trap and formatter reuse.

Read article →
Software Development

Python Abstract Class: ABC, abstractmethod and When to Use Them

Python abstract class explained: ABC and abstractmethod, abstract properties, shared logic with super, register, collections.abc and ABC vs Protocol, tested.

Read article →
Software Development

Python Subprocess Explained: run, Capture Output, Timeouts and Safety

Python subprocess explained with tested examples: run, capture_output, check, timeouts, input, environment, shell injection, encoding on Windows and Popen streaming.

Read article →
Databases & SQL

SQL EXPLAIN Plan: How to Read Query Plans and Fix Slow Queries

SQL EXPLAIN plan explained: read scans, index searches, covering indexes and temporary sorts, with before and after timings for five…

Read article →
Artificial Intelligence

Decision Tree in Python: Gini, Entropy and Overfitting From Scratch

Decision tree in Python from scratch: Gini impurity, entropy, information gain, best splits, readable rules, and how depth and leaf…

Read article →
Software Development

URL Query Parameters: Encoding, URLSearchParams and Common Traps

URL query parameters explained: reading and building them with URLSearchParams and urllib, percent encoding, plus signs, repeated keys and nine…

Read article →
DevOps

Git Blame Explained: Find Who Changed a Line, and Why

Git blame explained with a real repository: ignore whitespace, line ranges and functions, ignore-revs files for formatting commits, moved code…

Read article →
Test Automation

Pytest Benchmark: Measure Speed and Catch Performance Regressions

Pytest benchmark tutorial: the benchmark fixture, reading results, parametrized and pedantic benchmarks, saving baselines and failing the build on regressions.

Read article →
Software Testing

Defect Density: Formula, Worked Examples and How to Use It

Defect density explained: the formula, a five-module worked example, per KLOC vs per function point, severity weighting, defect removal efficiency…

Read article →
Databases & SQL

Case Insensitive Search in SQL: LOWER, LIKE, COLLATE and Indexes

Case insensitive search in SQL: LOWER, LIKE, COLLATE NOCASE and expression indexes compared with query plans, plus accented letters and…

Read article →
Databases & SQL

ON DELETE CASCADE in SQL: CASCADE vs SET NULL vs RESTRICT

ON DELETE CASCADE in SQL tested: CASCADE vs SET NULL vs RESTRICT, multi-level cascades, the SQLite foreign key pragma, row…

Read article →
Software Development

JavaScript BigInt Explained: Big Numbers, Division and JSON

JavaScript BigInt explained: the 2^53 limit, creating and converting BigInt, division, mixing types, JSON stringify and parse without losing digits,…

Read article →
Artificial Intelligence

Logistic Regression in Python: Sigmoid, Log Loss and Gradient Descent From Scratch

Logistic regression in Python from scratch: sigmoid, log loss, gradient descent, odds ratios, thresholds, sigmoid overflow and separable data, tested…

Read article →
DevOps

Git Worktree Explained: Work on Two Branches at Once

Git worktree explained: add, list, remove, prune, lock and detached worktrees, a hotfix workflow, and the errors you will hit,…

Read article →
Test Automation

Pytest ini Explained: addopts, markers, testpaths and Precedence

Pytest ini explained: testpaths, addopts, strict markers, xfail_strict, filterwarnings, minversion, config file precedence and command-line overrides, tested.

Read article →
Software Testing

Test Estimation Techniques: WBS, Three Point PERT and Monte Carlo

Test estimation techniques worked through: WBS, three point PERT, total uncertainty, a Monte Carlo check, percentage rules and Wideband Delphi.

Read article →
Databases & SQL

Gaps and Islands in SQL: Find Streaks and Missing Ranges

Gaps and islands in SQL: find login streaks and missing ranges with ROW_NUMBER, DENSE_RANK, LAG and LEAD, plus the duplicate…

Read article →
Databases & SQL

INSERT INTO SELECT in SQL: Copy Rows Between Tables Safely

INSERT INTO SELECT in SQL: copy rows between tables with chosen columns, joins and summaries, avoid duplicates on reruns, upsert,…

Read article →
Artificial Intelligence

Linear Regression in Python: Least Squares From Scratch, With R Squared

Linear regression in Python from scratch: closed form, NumPy least squares and gradient descent, R squared, RMSE, outliers and curved…

Read article →
DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

Git remote explained: add, set-url, separate push URLs, rename, remove and prune, plus how to avoid leaking tokens in remote…

Read article →
Test Automation

Pytest Mock: mocker.patch, spy, side_effect and autospec Explained

Pytest mock explained: mocker.patch, return_value, side_effect, spy, autospec and PropertyMock, with tested examples for APIs, clocks and retries.

Read article →
Software Testing

System Testing Explained: Types, Process and a Real End-to-End Example

System testing explained: types, entry and exit criteria, the process, and a real end-to-end test suite run against a small…

Read article →
Artificial Intelligence

Naive Bayes Classifier Explained: Build a Spam Filter in Python

Naive Bayes classifier explained by building a spam filter in Python: Bayes rule, the naive assumption, Laplace smoothing, log probabilities…

Read article →
DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

Git branch explained with tested commands: list, create, switch, rename, delete, merged checks, recovering deleted branches, remote tracking and naming.

Read article →
Test Automation

Pytest raises: Testing Exceptions, match and excinfo

Pytest raises explained with tested examples: match regexes, excinfo, custom and chained exceptions, parametrized error cases, pytest.warns and common mistakes.

Read article →
Software Testing

Non Functional Testing: Types, Metrics and a Real Load Test

Non functional testing explained: 10 key types, measurable requirements, latency percentiles and what a small real load test revealed about…

Read article →
Artificial Intelligence

K Means Clustering Explained: How It Works, With Python Code

K means clustering explained: the algorithm, a from-scratch NumPy version, choosing k with the elbow and silhouette methods, k-means++, scaling…

Read article →
DevOps

Git Log Explained: 15 Useful Commands and Pretty Formats

Git log explained with 15 tested commands: oneline, graph, filters by author, date, message and code, file history, stats, pretty…

Read article →
Test Automation

Pytest conftest.py Explained: Shared Fixtures, Hooks and Overrides

Pytest conftest.py explained with a tested suite: shared fixtures, scope and teardown, folder overrides, autouse, custom options, markers and useful…

Read article →
Software Testing

Usability Testing: Methods, Metrics, SUS Score and Checklist

Usability testing explained: methods, planning, writing tasks, running sessions, metrics, SUS scoring, how many users you need and a practical…

Read article →