- Get List of all Enum values in python
- Get List of all Enum values
- Frequently Asked:
- Get Names of all entries in Enum
- Get name/value pairs of all entries in Enum
- Summary
- Related posts:
- Share your love
- Leave a Comment Cancel Reply
- Terms of Use
- Disclaimer
- Python enum get all values
- # Table of Contents
- # Get Enum name by value in Python
- # Get a List of all Enum Values or Names in Python
- # Getting Enum Names and Values in Python
- # Additional Resources
- How to get all values from python enum class?
- Method 1: Using the Enum’s members attribute
- Method 2: Iterating over the Enum class
- Method 3: Using the Enum’s members attribute
- Method 4: Using the built-in dir() function
Get List of all Enum values in python
This tutorial will discuss about unique ways to get list of all enum values in Python.
Table Of Contents
Get List of all Enum values
Iterate over all entries in Enum in a List Comprehension. For each entry in enum, select its value property during iteration, to get the value field of each entry of enum. The List comprehension will return a list of all values of the Emum.
Let’s see the complete example,
from enum import Enum class ChannelStatus(Enum): IDE =1 ACTIVE = 2 BLOCKED = 3 WAITING = 4 CLOSED = 5 # Get list of all enum values in Python enumValues = [statusMem.value for statusMem in ChannelStatus] print (enumValues)
Frequently Asked:
Get Names of all entries in Enum
Iterate over all entries in Enum using a List Comprehension. During iteration, for each entry in enum, access its name property, to get the name field of that entry in enum. The List comprehension will return a list of all names of all entries in Emum.
Let’s see the complete example,
from enum import Enum class ChannelStatus(Enum): IDE =1 ACTIVE = 2 BLOCKED = 3 WAITING = 4 CLOSED = 5 # Get list of names of all enum values in Python enumValueNames = [statusMem.name for statusMem in ChannelStatus] print (enumValueNames)
['IDE', 'ACTIVE', 'BLOCKED', 'WAITING', 'CLOSED']
Get name/value pairs of all entries in Enum
Iterate over all entries in Enum using for loop, and for each enum entry, access its name and value properties to get the details. In the belowe example, we have printed all the names and value of all entries in the enum, one by one.
Let’s see the complete example,
from enum import Enum class ChannelStatus(Enum): IDE =1 ACTIVE = 2 BLOCKED = 3 WAITING = 4 CLOSED = 5 # iterate over all entries of name, and print # name, value of each entry in enum for status in ChannelStatus: print("Name : ", status.name, " :: Value : ", status.value)
Name : IDE :: Value : 1 Name : ACTIVE :: Value : 2 Name : BLOCKED :: Value : 3 Name : WAITING :: Value : 4 Name : CLOSED :: Value : 5
Summary
We learned about different ways to get a List of all Enum values in Python. Thanks.
Related posts:
Share your love
Leave a Comment Cancel Reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Terms of Use
Disclaimer
Copyright © 2023 thisPointer
To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
Python enum get all values
Last updated: Feb 18, 2023
Reading time · 4 min
# Table of Contents
# Get Enum name by value in Python
To get an enum name by value, pass the value to the enumeration class and access the name attribute, e.g. Sizes(1).name .
When the value is passed to the class, we get access to the corresponding enum member, on which we can access the name attribute.
Copied!from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 print(Sizes(1).name) # 👉️ SMALL print(Sizes(2).name) # 👉️ MEDIUM print(Sizes(3).name) # 👉️ LARGE
The Sizes(1) syntax allows us to pass an integer to the class and get the corresponding enum member.
Copied!from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 value = 1 print(Sizes(value)) # 👉️ Sizes.SMALL print(Sizes(value).name) # 👉️ SMALL
This is useful when you don’t know the name of the enum member ahead of time (because it’s read from a file or fetched from an API).
# Get a List of all Enum Values or Names in Python
Use a list comprehension to get a list of all of an enum’s values or names.
On each iteration, access the value or name attributes on the enum member to get a list of all of the enum’s values or names.
Copied!from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 values = [member.value for member in Sizes] print(values) # 👉️ [1, 2, 3] names = [member.name for member in Sizes] print(names) # 👉️ ['SMALL', 'MEDIUM', 'LARGE']
On each iteration, we access the value attribute to get a list of all of the enum’s values.
Similarly, we can access the name attribute on each iteration to get a list of all of an enum’s names.
List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.
You can use the same approach if you need to get a list of tuples containing the name and value of each enum member.
Copied!from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 result = [(member.name, member.value) for member in Sizes] # 👇️ [('SMALL', 1), ('MEDIUM', 2), ('LARGE', 3)] print(result)
The first element in each tuple is the name, and the second is the value of the enum member.
Use the in operator if you need to check if a value is in an enum.
Copied!from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 values = [member.value for member in Sizes] print(values) # 👉️ [1, 2, 3] if 2 in values: # 👇️ this runs print('2 is in values')
The in operator tests for membership. For example, x in l evaluates to True if x is a member of l , otherwise it evaluates to False .
You can use a simple for loop if you need to iterate over an enum.
Copied!from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 for size in Sizes: print(size) print(size.name, size.value)
# Getting Enum Names and Values in Python
To access an enum’s names and values:
- Use dot notation to access a specific enum member, e.g. Sizes.SMALL .
- Use the name and value properties to access the enum’s names and values.
Copied!from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 # ✅ Get Enum name print(Sizes.SMALL.name) # 👉️ SMALL # 👇️ access enum name by value print(Sizes(1).name) # 👉️ SMALL print(Sizes['SMALL'].name) # 👉️ SMALL # --------------------------------- # ✅ Get Enum value print(Sizes.SMALL.value) # 👉️ 1 print(Sizes['SMALL'].value) # 👉️ 1
As shown in the code sample, you can use the name and value properties on an enum member to get the enum’s name and value.
Copied!from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 print(Sizes.MEDIUM.name) # 👉️ MEDIUM print(Sizes.MEDIUM.value) # 👉️ 2
You can also use square brackets to access enum members.
Copied!from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 name = 'LARGE' print(Sizes[name].name) # 👉️ MEDIUM print(Sizes[name].value) # 👉️ 2
This is useful when you don’t know the name of the enum member ahead of time (because it’s read from a file or fetched from an API).
If you only have the value that corresponds to the enum member, pass it to the enumeration class and access the name attribute.
Copied!from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 print(Sizes(1).name) # 👉️ SMALL print(Sizes(2).name) # 👉️ MEDIUM print(Sizes(3).name) # 👉️ LARGE
This is only necessary when you need to get the name of an enum member by its value.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
How to get all values from python enum class?
Enum is a Python module that provides support for enumerated types, which are a set of named constants that represent unique values in a program. They are a useful way of representing a set of related values and are often used in situations where a particular value is used in multiple places in a codebase. Enums are implemented in Python as classes and can be used to define a set of values that are associated with a unique identifier. In some cases, it may be necessary to retrieve all of the values from an Enum class in Python. In this article, we will look at different methods for obtaining all of the values from an Enum class in Python.
Method 1: Using the Enum’s members attribute
To get all values from a Python Enum class, you can use the Enum’s members attribute. Here’s an example:
from enum import Enum class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 values = [color.value for color in Color] print(values)
In the above example, we define a Color Enum class with three members: RED , GREEN , and BLUE . We then use a list comprehension to extract the value attribute of each member and store it in a list called values .
Another way to get all values from an Enum class is to use the list() function on the Enum’s __members__ attribute. Here’s an example:
from enum import Enum class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 values = list(Color.__members__.values()) print(values)
[Color.RED: 1>, Color.GREEN: 2>, Color.BLUE: 3>]
In the above example, we use the list() function to convert the values() view of the __members__ attribute to a list. This gives us a list of Color Enum members.
Overall, using the Enum’s members attribute or the list() function on the Enum’s __members__ attribute are both good ways to get all values from a Python Enum class.
Method 2: Iterating over the Enum class
To get all values from a Python Enum class, you can iterate over the class using a for loop. Here’s an example:
from enum import Enum class Colors(Enum): RED = 1 GREEN = 2 BLUE = 3 for color in Colors: print(color)
Colors.RED Colors.GREEN Colors.BLUE
You can also get the values as a list using a list comprehension:
values = [color.value for color in Colors] print(values)
If you want to get the names of the values, you can use the name attribute:
names = [color.name for color in Colors] print(names)
And if you want both the names and values, you can use a dictionary comprehension:
names_values = color.name: color.value for color in Colors> print(names_values)
That’s it! By iterating over the Enum class, you can easily get all the values, names, or both.
Method 3: Using the Enum’s members attribute
To get all values from a Python Enum class using the Enum’s __members__ attribute, you can follow these steps:
import enum class MyEnum(enum.Enum): VALUE1 = 1 VALUE2 = 2 VALUE3 = 3
- Access the __members__ attribute of the Enum class to get a dictionary that maps the names of the enum members to their corresponding values.
members = MyEnum.__members__
import enum class MyEnum(enum.Enum): VALUE1 = 1 VALUE2 = 2 VALUE3 = 3 members = MyEnum.__members__ values = members.values() values_list = list(values) print(values_list) # Output: [, , ]
You can also use a list comprehension to extract the values directly from the __members__ attribute:
values_list = [member.value for member in MyEnum]
This code will produce the same output as the previous example:
print(values_list) # Output: [1, 2, 3]
Method 4: Using the built-in dir() function
To get all values from a Python Enum class using the built-in dir() function, you can follow these steps:
from enum import Enum class Colors(Enum): RED = 1 GREEN = 2 BLUE = 3
enum_values = [attr for attr in dir(Colors) if not callable(getattr(Colors, attr)) and not attr.startswith("__")]
print(enum_values) # ['RED', 'GREEN', 'BLUE']
- dir() returns a list of attributes and methods of an object.
- We filter the list to exclude any callable methods or attributes that start with __ , which are not enum values.
- The resulting list contains only the enum values.
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 EXTRA_LARGE = 4 enum_values = [attr for attr in dir(Sizes) if not callable(getattr(Sizes, attr)) and not attr.startswith("__")] print(enum_values) # ['SMALL', 'MEDIUM', 'LARGE', 'EXTRA_LARGE']