Creating Enumerations in Python
Enum module defines a general purpose enumeration type with iteration and comparison capabilities. You can use this type to create sets of named constants that you can use to replace literals of common data types, such as numbers and strings.
A classic example of when you should use an enumeration is when you need to create a set of enumerated constants representing the days of the week. Each day will have a symbolic name and a numeric value between one and seven inclusive. On screen you can see how to create this enumeration by using
Enum as your superclass or parent class.
Are enumeration members also known as
Enum members or just members? Each member must have a value which needs to be constant. Often the values mapped to members are consecutive integer numbers, however, they can be of any type, including user-defined types.
In this example, the value of
Day.MONDAY is one,
Day.TUESDAY is two, and so on. Because enumeration members must be constants, Python doesn’t allow you to assign new values to members at runtime.
In this example, the
Enum type is a hub for enumeration members, which happen to be of the type
Day. Unlike member names, the name containing the enumeration itself isn’t a constant but a variable.
So it’s possible to rebind this name at any moment during your program’s execution, but you should avoid doing that as you’ve just seen. You’ve reassigned
Day, which now holds a string rather than the original enumeration.
range is used with the start and stop arguments. The start argument allows you to provide the number that starts the range, while the stop argument defines the number at which the range will stop generating numbers.
Even though you use the class syntax to create enumerations, they’re special classes that differ from normal Python classes. Unlike regular classes,
Enums can’t be instantiated can’t be subclassed unless the base
Enum has no members provide a human-readable string representation for their members.
03:58 They’re iterable, returning their members in a sequence. They provide hashable members that can be used as dictionary keys. They support the square bracket syntax, call syntax, and dot notation to access their members, and they don’t allow member reassignments.
04:16 You should keep all these subtle differences in mind when you start creating and working with your own enumerations in Python. While members often take consecutive integer values, it’s possible that the values can be of any type, including user-defined types.
Become a Member to join the conversation.