Enums and Named Tuples
Represent fixed choices with enums and create readable, tuple-like records with NamedTuple.
In this lesson, you will learn
- ✓Explain when to use an Enum to represent a fixed set of named choices.
- ✓Distinguish an enum member's name from its associated value.
- ✓Access, compare, and iterate over enum members and handle invalid values.
- ✓Create NamedTuple records with named fields and type annotations.
- ✓Explain NamedTuple indexing, unpacking, immutability, and default values.
- ✓Choose appropriately between an enum, a named tuple, and an ordinary tuple.
1. What Is an Enum?
An enumeration, usually called an enum, represents a fixed collection of named members. It is useful when a value should come from a known set of choices, such as PENDING, APPROVED, and REJECTED.
Python provides Enum in the standard-library enum module. To define an enum, import Enum and create a class that inherits from it. Each attribute assigned inside the class becomes an enum member.
An enum member has a name and an associated value. In `Status.PENDING = 'pending'`, the member name is PENDING and its value is the string 'pending'. The name is the identifier used in Python code; the value is the data associated with that member.
Enum members make code easier to read because `Status.APPROVED` communicates intent more clearly than an unexplained string such as 'approved'. They also provide a central place to define the allowed choices.
Defining an enum does not automatically validate every external input in your application. If a user or API supplies a status, your program must still decide how to convert or reject that input.
Define and use an enum
`Enum` is imported from Python's standard-library enum module. `Status` defines three named members. `Status.PENDING` refers to an enum member, not just the string 'pending'. Printing a member displays its enum class and member name.
Note
2. Comparing, Iterating Over, and Looking Up Enum Members
Enum members can be compared directly with other members. For an ordinary Enum, compare members of the same enum when checking which choice is selected.
For example, `current_status == Status.APPROVED` checks whether `current_status` is the APPROVED member. Comparing the member with the plain string 'approved' is not the same check: an ordinary Enum member is not equal to its string value.
You can iterate over an enum class to visit its defined members. This is useful for displaying available choices or testing each defined status.
You can also construct an enum member from its associated value by calling the enum class with that value, such as `Status('approved')`. If no member has that value, Python raises `ValueError`.
When reading a member by its declared name, use square-bracket lookup such as `Status['APPROVED']`. If the name does not exist, Python raises `KeyError`. Remember that name lookup uses the member name, whereas value lookup uses the associated value.
Compare enum members
`current` refers to the APPROVED enum member. The comparison checks whether it equals `Status.APPROVED`. The condition is true, so the first message is printed.
3. Handle Invalid Enum Values
Enum classes are useful for representing a defined set of choices, but external input may not match one of those choices.
Suppose an application receives a status string from a form. Calling `Status(user_input)` attempts to find the enum member associated with that value. A valid value produces a member; an unknown value raises `ValueError`.
Use a try/except block when invalid values are expected and should be handled gracefully. Catch the specific exception you expect instead of catching every possible exception without a reason.
Do not confuse a member's name with its value. If the declared name is APPROVED and the associated value is 'approved', `Status['APPROVED']` looks up by name, while `Status('approved')` looks up by value.
Safely handle an unknown value
`user_input` contains 'cancelled', which is not an enum value defined in Status. `Status(user_input)` raises `ValueError`. The except block handles that specific error and displays `Unknown status`. The program does not print `status.name` because the failed assignment does not complete.
Caution
4. What Is a Named Tuple?
A tuple groups multiple values into one object. A normal tuple such as `('Asha', 22)` is compact, but it does not explain what each position means unless the reader already knows the structure.
A named tuple adds field names to a tuple-like record. Python's `typing.NamedTuple` lets you define a class with named fields and type annotations.
For example, a Student record can have a `name` field and an `age` field. You can access these fields using `student.name` and `student.age` instead of remembering that the name is at index 0 and the age is at index 1.
A NamedTuple instance is still tuple-like: it supports indexing, iteration, unpacking, and comparison with other tuples by their elements. It also provides named attributes, making the data easier to read.
NamedTuple is a good choice for simple records whose fields should not be reassigned after construction. If you need mutable attributes or more involved behavior, consider whether a regular class or a dataclass would be a better fit.
Create a named tuple
`Student` defines a named-tuple type with two fields. `name: str` describes the intended type of the name field. `age: int` describes the intended type of the age field. `Student('Asha', 22)` constructs an instance with those field values. Dot notation accesses each field by its name.
Note
5. Named Tuples Support Unpacking but Are Immutable
Because a named tuple is tuple-like, you can unpack its fields into separate variables. The number of target variables must match the number of values being unpacked.
You can also pass a named tuple to code that expects an ordinary tuple of compatible length and contents. Named tuples provide extra field names without abandoning tuple behavior.
Named tuples are immutable. After an instance has been created, you cannot assign a new value to one of its fields. For example, assigning `student.age = 23` raises `AttributeError`.
Immutability applies to the tuple's field bindings. If a field refers to a mutable object, that object's contents may still be mutable. For simple records containing strings and integers, this distinction is usually straightforward.
If you need to update a named-tuple field, create a new instance with the desired values rather than attempting to change the existing instance.
Unpack a named tuple
`student` contains two values in a fixed order. `name, age = student` unpacks the first field into `name` and the second into `age`. The print statements display the unpacked values on separate lines.
Caution
6. Named Tuple Defaults and Type Hints
NamedTuple fields can have default values. Fields with defaults must come after fields without defaults in the class definition.
A default makes the corresponding constructor argument optional. If a field has a default, you can omit that argument when constructing the record and Python uses the default value.
Type annotations document the intended field types, but they do not automatically validate all values passed to the constructor. For example, a field annotated as `age: int` does not by itself guarantee that an integer was supplied.
For simple records with fixed fields, NamedTuple provides a concise combination of named access and tuple behavior. A dataclass is often more suitable when you want records that can be mutable or have richer class behavior.
Use a default field value
`name` and `price` have no defaults and must be supplied. `in_stock` defaults to True, so the first instance can omit that argument. The second instance explicitly passes False, overriding the default for that instance. The field order places the field with a default after the fields without defaults.
Note
7. Enum vs NamedTuple vs Ordinary Tuple
An Enum and a NamedTuple solve different problems. An Enum represents one choice from a fixed set of named members. A NamedTuple groups several related values into a single record.
Use an Enum when the possible choices are known in advance, such as PENDING, APPROVED, and REJECTED. Use a NamedTuple when you need a record such as a Point with x and y fields or a Student with name and age.
Use an ordinary tuple for a simple ordered group of values when field names would add little clarity. If you repeatedly need to remember what each tuple position means, a NamedTuple can improve readability.
Neither Enum nor NamedTuple replaces input validation or good program design. Choose the structure that best expresses the data and rules your application actually needs.
Choose the right structure
`OrderStatus` defines the finite set of allowed status members. `OrderSummary` groups an order ID and a status into one record. The `status` field contains an enum member, so its name and value can be accessed through that member. This example combines the two tools because each serves a distinct purpose.
Common pitfalls to avoid
Real debugging lessons and exact syntax contrasts to avoid runtime bugs
#1 Confusing an enum member's name with its value.
Why it happens: An enum member's name is its identifier in the enum definition, while its value is the data assigned to that member.
Key takeaway: Use `.name` for the declared member name and `.value` for its associated value.
#2 Comparing an ordinary Enum member directly with its associated string.
Why it happens: Ordinary Enum members are not automatically equal to their associated string values; compare the member or explicitly inspect its .value.
Key takeaway: Compare enum members with the corresponding enum member, or explicitly access `.value` when comparing with the underlying value is intended.
#3 Assuming an unknown enum value produces a default member automatically.
Why it happens: Looking up an unknown value raises ValueError by default, so provide explicit fallback or error handling if unknown values are expected.
Key takeaway: Handle invalid value lookups explicitly, for example by catching `ValueError` when constructing a member from an unknown value.
#4 Using the wrong lookup method for an enum.
Why it happens: Enum lookup by value uses EnumClass(value), while lookup by name uses EnumClass['NAME']; choose based on the input you have.
Key takeaway: Use `Status['APPROVED']` to look up by declared member name and `Status('approved')` to look up by associated value.
#5 Using numeric indexes for every named-tuple field even when the meaning is not obvious.
Why it happens: NamedTuple fields have names that communicate meaning, so named access is usually clearer than numeric indexing.
Key takeaway: Prefer readable attribute access such as `student.age` when the field's meaning matters.
#6 Trying to assign a new value to a NamedTuple field.
Why it happens: NamedTuple instances are tuple-like and immutable, so create a new instance rather than assigning to a field.
Key takeaway: NamedTuple instances are immutable. Construct a new instance when you need different field values.
#7 Placing a field without a default after fields with defaults.
Why it happens: Like ordinary function parameters, required named-tuple fields must precede fields with defaults.
Key takeaway: Define required fields first and fields with defaults afterward.
#8 Assuming type annotations validate all NamedTuple constructor arguments.
Why it happens: NamedTuple annotations help static analysis but do not automatically validate every runtime argument or nested value.
Key takeaway: Use annotations for documentation and static analysis. Perform explicit runtime validation if the application requires it.
Ready for hands-on challenges?
Test your skills with shuffled coding challenges in the Practice Arena.
Technical and placement interview questions
Frequently tested interview questions with detailed, full answers (click to expand)
Q1:What is an Enum in Python?
Q2:What is the difference between an enum member's name and its value?
Q3:How do you retrieve an enum member by name or by value?
Q4:What is a NamedTuple?
Q5:What is the difference between a tuple and a NamedTuple?
Q6:Are NamedTuple instances mutable?
Q7:Can a NamedTuple field have a default value?
Q8:Do NamedTuple annotations enforce field types at runtime?
Q9:When would you choose an Enum instead of a NamedTuple?
Q10:How does a NamedTuple differ from a dataclass?
Key takeaways
- Enum represents a fixed set of named members and makes choices more explicit.
- Use `.name` to access an enum member's declared name and `.value` to access its associated value.
- Iterate over an enum to visit its defined members.
- Look up enum members by name with square brackets or by value by calling the enum class.
- Handle invalid enum lookups with the appropriate exception handling when necessary.
- NamedTuple groups related values into an immutable, tuple-like record with named fields.
- Named tuples support attribute access, indexing, unpacking, and tuple-like operations.
- Fields with defaults must follow fields without defaults.
- Enum, NamedTuple, ordinary tuples, and dataclasses solve different problems; choose according to the structure and behavior your program needs.
- Type annotations document intended types but do not automatically validate all runtime values.
Related Topics & Next Steps
4 Recommended LessonsStrengthen your Python foundation with these complementary core lessons: