How to Convert Python Enums to Strings and Viceversa
Python's Enum
class allows for symbolic names bound to unique values. Sometimes, you may need to convert these enum members to strings or back to enum members.
This guide covers:
- Converting Enums to Strings: How to access the enum's name and value, and how to customize string representation with
__str__()
. - Converting Strings to Enums: How to convert a string into an enum member by its name or value.
These conversions are useful in various scenarios like display, serialization, and logging. Let's explore how to handle both cases.
How to Convert Python Enums to Strings
This section explains how to convert Python Enum
members to their string representations. We'll cover accessing the .name
and .value
attributes, and how to customize the string representation using __str__()
.
Accessing Enum Member Name and Value
from enum import Enum
class Color(Enum):
RED = 'stop'
GREEN = 'go'
YELLOW = 'get ready'
print(Color.RED) # Output: Color.RED (default representation)
print(repr(Color.RED)) # Output: <Color.RED: 'stop'> (shows value)
print(Color.RED.name) # Output: RED (string name)
print(Color.RED.value) # Output: stop (string value)
Color.RED
: Accessing the enum member directly gives you the enum member itself (e.g.,Color.RED
). The default string representation of this isClassName.MemberName
.Color.RED.name
: The.name
attribute gives you the name of the enum member as a string (e.g., "RED", "GREEN"). This is usually what you want when converting to a string for display.Color.RED.value
: The.value
attribute gives you the value associated with the enum member (e.g., 'stop', 'go').
You can also access enum values using the square bracket syntax:
value = 'RED'
print(Color[value].value) # Output: stop
Custom String Representation with __str__()
If you want str(Color.RED)
or print(Color.RED)
to directly output the value (or any other custom string), define the __str__()
method in your enum class:
from enum import Enum
class Color(Enum):
RED = 'stop'
GREEN = 'go'
YELLOW = 'get ready'
def __str__(self):
return str(self.value) # Return the value as a string
print(Color.RED) # Output: stop (now uses __str__)
print(str(Color.RED)) # Output: stop
- The
__str__()
method returns a string that will represent the object.
How to Convert Strings to Enum Members
This section explains how to convert a string to an enum member in Python, covering both the case where the string represents the enum member's name and the case where it represents the value.
Converting a String to an Enum Member by Name
Use square bracket notation with the enum class:
from enum import Enum
class Sizes(Enum):
SMALL = 'sm'
MEDIUM = 'md'
LARGE = 'lg'
name = 'MEDIUM'
print(Sizes[name]) # Output: Sizes.MEDIUM
print(Sizes[name].value) # Output: md
Sizes['MEDIUM']
directly accesses the enum member whose name is 'MEDIUM'. This is the standard and most efficient way to do this.
Converting a String to an Enum Member by Value
This is a bit more involved, as enums are designed for lookup by name, not value.
Inheriting from str
and Enum
If you extend the Enum class from the str
class, you can directly compare the enum member with the string.
from enum import Enum
class Color(str, Enum): # Inherit from str and Enum
RED = 'stop'
GREEN = 'go'
YELLOW = 'get ready'
my_str = 'go'
if my_str == Color.GREEN: # Direct comparison!
print('success') # Output: success
print(my_str == Color.YELLOW) # Output: False
- The
str
class must be the first argument when extending the class.
Using the .value
Attribute
from enum import Enum
class Color(Enum):
RED = 'stop'
GREEN = 'go'
YELLOW = 'get ready'
my_str = 'go'
if my_str == Color.GREEN.value:
print('success') # Output: success
- In this case, you compare the string with the return value of
.value
attribute.