Getting to Know Enumerations
Several programming languages such as Java and C++ have a native enumeration or
enum data type as part of their syntax. This allows you to create sets of named constants, which are considered members of the containing
00:17 You can access the members through the enumeration itself. Enumerations come in handy when you need to define an immutable and discrete set of similar or related constant values that may or may not have semantic meaning in your code. Days of the week, months, seasons of the year, Earth’s cardinal directions, program status codes, HTTP status codes, colors in a traffic light, and pricing plans of a web service are all great examples of enumerations in programming.
01:18 This addition to the standard library, you could create something similar to an enumeration by defining a sequence of similar or related constants. Python developers often use the idiom seen on screen.
01:38 Even though this works, it doesn’t scale well when you are trying to group a large number of related constants. Another inconvenience is that the first constant will have a value of zero, which is falsy in Python.
If you’re using a Python version prior to 3.4, then you can create enumerations by installing the
enum34 library, which is a backport of the standard library
aenum third-party library could be an option for you as well.
Enumerations have several benefits, some of which relate to ease of coding, allowing for conveniently grouped related constants in a kind of namespace, allowing for additional behavior with custom methods that operate on either
enum members or the
02:34 enabling direct iteration over members, including their names and values, facilitating code completion within IDEs and editors, enabling type and error checking with static checkers, providing a hub of searchable names and mitigating spelling mistakes when using the members of an enumeration.
They also provide a number of benefits, ensuring constant values that can’t be changed during the code’s execution, guaranteeing type safety by differentiating the same value shared across several
enums, improving readability and maintainability by using descriptive names instead of mysterious values or magic numbers.
Now that you know the basics of enumerations in programming and in Python, you can start creating your own
enum types by using Python’s
Enum class, and that’s what you’ll be doing in the next part of the course.
Become a Member to join the conversation.