Represent Closed States with Enum
Core idea
An Enum associates symbolic members with values. Access a member by attribute, look up its name with brackets, or look up a value by calling the enum class. Equal values normally create aliases of the first member. Iteration lists canonical members; members also exposes aliases. Use @unique to reject aliases when every name must be distinct.
from enum import Enumclass State(Enum): QUEUED='queued' SENT='sent'print(State('sent') is State.SENT)print(State['QUEUED'].value)Calling the class looks up a value; indexing looks up the member name.
Inspect aliases
from enum import Enumclass Status(Enum): READY=1 AVAILABLE=1 BUSY=2print(Status.AVAILABLE is Status.READY)print([s.name for s in Status])print(list(Status.__members__))The second name points to the same member; ordinary iteration omits aliases.
Common mistake
An ordinary Enum member is not its raw value. Handle unknown external values with a deliberate error policy rather than silently defaulting to a valid state.
Practice
Define a three-state shipment enum and try valid and unknown values; then add an accidental alias and detect it with @unique.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Enum members and aliases
Check your understanding of enum members and aliases.
What is printed?
from enum import Enumclass A(Enum): X=1 Y=1print(A.Y.name)What is printed?
from enum import Enumclass A(Enum): X=1print(A(1) is A.X)Which syntax looks up a member by name?
What does @unique reject?