Convert a String to an Enum in Python

avatar

Borislav Hadzhiev

Last updated: Jun 17, 2022

banner

Photo from Unsplash

Convert a String to an Enum in Python #

To convert a string to an enum in Python:

  1. Import the Enum class from the enum module.
  2. Declare an enum by extending the Enum class.
  3. Assign class properties on the enum class.
main.py
from enum import Enum class Sizes(Enum): SMALL = 'sm' MEDIUM = 'md' LARGE = 'lg' # 👇️ human readable string representation print(Sizes.MEDIUM) # 👉️ Sizes.MEDIUM # 👇️ repr() shows the value as well print(repr(Sizes.MEDIUM)) # 👉️ <Sizes.MEDIUM: 'md'> # 👇️ get name of enum print(Sizes.MEDIUM.name) # 👉️ MEDIUM # 👇️ get value of enum print(Sizes.MEDIUM.value) # 👉️ md # 👇️ if enum value is int, you can convert it to str print(str(Sizes.MEDIUM.value)) # 👉️ md # 👇️ access enum member using a string print(Sizes['LARGE'].value) # 👉️ lg

Enums are created using the class syntax and enum members (e.g. Sizes.SMALL) can be anything: int, str, etc.

The example creates an enumeration with 3 members that all have values of type string.

You can use the name and value properties on an enum member to get the enum's name and value.

You can also use square brackets to access enum members.

main.py
from enum import Enum class Sizes(Enum): SMALL = 'sm' MEDIUM = 'md' LARGE = 'lg' name = 'MEDIUM' print(Sizes[name].value) # 👉️ md print(Sizes['LARGE'].value) # 👉️ lg
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).

Here is an example that takes a string from user input and uses it to access an enum member.

main.py
from enum import Enum class Sizes(Enum): SMALL = 'sm' MEDIUM = 'md' LARGE = 'lg' name = input('SMALL, MEDIUM or LARGE: ') print(name) # 👉️ small print(Sizes[name.upper()]) # 👉️ Sizes.SMALL print(Sizes[name.upper()].value) # 👉️ sm

You can use a simple for loop if you need to iterate over an enum.

main.py
from enum import Enum class Sizes(Enum): SMALL = 'sm' MEDIUM = 'md' LARGE = 'lg' for size in Sizes: print(size) print(size.name, size.value)

You can use a list comprehension to check if a specific value is in an enum.

main.py
from enum import Enum class Sizes(Enum): SMALL = 'sm' MEDIUM = 'md' LARGE = 'lg' # 👇️ check enum member type print(type(Sizes.MEDIUM)) # 👉️ <enum 'Sizes'> # 👇️ check if member belongs to Enum print(isinstance(Sizes.MEDIUM, Sizes)) # 👉️ True values = [member.value for member in Sizes] print(values) # 👉️ ['sm', 'md', 'lg'] if 'md' in values: # 👇️ this runs print('md is in values')

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.