Explain Codes LogoExplain Codes Logo

Convert string to Enum in Python

python
enum
advanced-techniques
best-practices
Anton ShumikhinbyAnton Shumikhin·Jan 24, 2025
TLDR

To convert a string to an Enum in Python, employ the Enum class's lookup functionality via __members__. It's as simple as this:

from enum import Enum class Color(Enum): RED = 1 GREEN = 2 BLUE = 3 extracted_color_str = 'RED' resulting_color_enum = Color.__members__[extracted_color_str] # Voila! String transformed to Enum # Let's see if our magic trick worked! assert resulting_color_enum is Color.RED # If this is True, give yourself a high five!

Make sure to replace 'RED' with the string you're aiming to convert. Remember, the Enum member name must align precisely with the string. The command Color.__members__[color_str] shall do the trick!

Advanced techniques and precautions

Catering to lowercase and uppercase entries

By nature, Enum member names are case-sensitive. 'RED' and 'red' are regarded as two distinct members. For accommodating all kinds of user inputs, you can:

  • Convert the user's input to a single case:
extracted_color_str = input_color_string.upper() # Exactly! The louder, the better! resulting_color_enum = Color[extracted_color_str]
  • Alternatively, create a custom conversion method:
class Color(Enum): RED = 1 # Adding more colors here would turn this into a rainbow party! @staticmethod def from_string(s: str): return Color[s.upper()] # Loud and clear! resulting_color_enum = Color.from_string('red') # Yep, even whispers are heard!

Dealing with unknown entities

When unsure whether the string corresponds to a Enum member, enclose the conversion process within a try-except block. Catch the KeyError that pops up when trying to find an elusive Enum member:

try: resulting_color_enum = Color[extracted_color_str] except KeyError: # Woah! It's like looking for a unicorn! # Handle the error (maybe assign a default value) resulting_color_enum = Color.DEFAULT # Plan B activated!

Advantages of StrEnum

With Python 3.11, StrEnum is introduced to make string to Enum instance creation a cakewalk. Check this out:

from enum import StrEnum, auto class Color(StrEnum): RED = auto() # Let Python do the heavy lifting! Auto, the new autobot! GREEN = auto() BLUE = auto() extracted_color_str = 'RED' resulting_color_enum = Color(extracted_color_str) # All hail StrEnum!

StrEnum allows us to craft Enum instances directly using string values, making our job a lot easier!

Custom solutions and potential issues

Utilizing Enum subclasses

Desire to automate or modify the string to Enum conversion process? Create Enum subclasses that come with custom functions:

class EnhancedEnum(Enum): # Enum, with a cherry on top! @classmethod def from_string(cls, value: str): # Add your custom mapping logic right here! Don't hold back! return cls[value.upper()] # Shout. It. Out! class Color(EnhancedEnum): # Regular Enum: "Am I a joke to you?" RED = 1 GREEN = 2 BLUE = 3 # Make use of the custom method! resulting_color_enum = Color.from_string('green') # Enter the matrix. Get into the game.

"Eval" isn't your best friend

eval() might allure with its shiny promise of direct conversion, but stay away. It spells security risks and maintainability mishaps. It's like dabbling in dark magic!

Non-1-to-1 mappings

When String to Enum mappings aren't love at first sight (or 1-to-1), handle this within a custom method. Say no to confusion and yes to clear conversions:

class Color(Enum): LIGHT_RED = 1 DARK_GREEN = 2 PALE_BLUE = 3 # Who knew colors could be pale? @staticmethod def from_description(description: str): mapping = { # Map like you've never mapped before! 'red': Color.LIGHT_RED, 'green': Color.DARK_GREEN, 'blue': Color.PALE_BLUE, } # If not found, return none. Not all who wander are lost! return mapping.get(description.lower(), None)