Creating More Enumerations
00:00
More enumeration creation. You’ve already seen enumerations with int
s and strings, but you can also create enumerations of Boolean values. In this case, the members of your enumeration will have only two values.
00:24 In this example, anyone reading the code will know that it emulates a switch object with two possible states. This additional information improves the code’s readability.
00:39 The same goes for this example, making it clear that the response is yes or no. You can also define an enumeration with heterogeneous values.
00:58 However, this practice makes your code inconsistent from a type safety perspective, so it’s not recommended. Ideally, it would help if you had values of the same data type, which is consistent with the idea of grouping similar related constants in enumerations. You can also create empty enumerations.
01:22
In this example, Empty
represents an empty enumeration because it doesn’t define any member constants. Note that you can use the pass
statement, the ellipsis literal, or a class-level docstring to create empty enumerations.
01:43 The last approach can help you improve the readability of your code by providing extra content in the docstring. But why would you need to define an empty enumeration?
01:53 They can come in handy when you need to build a hierarchy of enum classes to reuse functionality through inheritance. Consider this example
02:09
here. You create BaseEnum
as an enumeration with no members. You can only subclass a custom enumeration if it doesn’t have members. So BaseEnum
qualifies.
02:25
The Alphabet
class inherits from the empty enumeration, which means that you can access the .as_list()
method. This method converts the value of a given member into a list.
02:45 In the next section of the course, you’ll take a look at another feature of Python’s enumerations, the functional API.
Become a Member to join the conversation.