Working With Enumerations in Python
00:00 Working with Enumerations in Python. When it comes to using enumerations in your code, accessing their members is a fundamental operation to perform. You’ll have three different ways to access enumeration members in Python.
This shows how you can access an
Enum member using the dot notation, which is pretty intuitive and readable. This line accesses the target member by calling the enumeration with the member’s value as an argument.
00:37 And a third access method is to use subscript notation. Python’s Enumerations offer great flexibility for you to access members. The dot notation is arguably the most commonly used approach in Python code, but the other two approaches can be helpful as well.
00:56 So use the notation that fulfills your specific needs, conventions, and style. It’s important to note that calling an enumeration with a member’s value as an argument can make you feel like you are instantiating the enumeration.
Trying to create an instance of an existing enumeration isn’t allowed, so you get a
TypeError if you attempt to do it. So you mustn’t confuse instantiating with accessing members through an enumeration call.
The members of a Python enumeration are instances of their containing class. During the
Enum class parsing, each member is automatically provided with a
.name attribute that holds the member’s name as a string. Members also get a
.value attribute that stores the value assigned to the member itself.
In the class definition, you can access
.value as you would do with a regular attribute using the dot notation. Take a look at this example, which simulates a semaphore, commonly known as a traffic light.
02:15 These attributes come in handy when you’re iterating through your enumerations, which you’ll explore next. One useful feature of Python’s enumerations compared to regular classes is that enumerations are iterable by default.
Because of this, you can use them in
for loops and with other tools that accept and process iterable objects. Python’s enumerations support direct iteration over members in the definition order.
03:09 This looks pretty similar to iterating over a dictionary, so if you are familiar with dictionary iteration, then looping over enumerations using this technique will be a straightforward task with many potential use cases.
03:35 The difference between iterating over this dictionary and the enumeration directly is that the dictionary gives you access to all members of the enumeration, including all of the aliases that you may have.
Become a Member to join the conversation.