Borislav Hadzhiev
Fri Jun 17 2022·2 min read
Photo by Nicholas Bartos
Use the functional API to construct an enum from a dictionary, e.g.
Sizes = Enum('Sizes', my_dict)
. The first argument we pass to the Enum
class
is the name of the enumeration, and the second - the source of the enumeration
member names and values.
from enum import Enum my_dict = { 'SMALL': 1, 'MEDIUM': 2, 'LARGE': 3 } Sizes = Enum('Sizes', my_dict) print(Sizes) # 👉️ <enum 'Sizes'> print(Sizes.SMALL.name) # 👉️ SMALL print(Sizes.SMALL.value) # 👉️ 1
We used the functional API for enum creation.
Enum
class is callable and takes the name of the enumeration as the first argument and the source of enumeration names as the second.The second argument can be:
The Sizes
enum we created using the functional API is equivalent to the
following enum.
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 print(Sizes.SMALL.name) # 👉️ SMALL print(Sizes.SMALL.value) # 👉️ 1
If we pass a dictionary to the functional API, we assign the values of the dictionary as the values for the corresponding keys.
If we use a whitespace-separated string of names or a sequence of names, the
enum values get auto-assigned increasing integers starting with 1
.
from enum import Enum Sizes = Enum('Sizes', 'SMALL MEDIUM LARGE') print(Sizes) # 👉️ <enum 'Sizes'> print(Sizes.SMALL.name) # 👉️ SMALL print(Sizes.SMALL.value) # 👉️ 1 print(Sizes.MEDIUM.name) # 👉️ MEDIUM print(Sizes.MEDIUM.value) # 👉️ 2
The code sample creates the same enum as in the previous examples.
You can optionally pass a start
argument to the functional API if you need to
specify a different starting value.
from enum import Enum Sizes = Enum('Sizes', 'SMALL MEDIUM LARGE', start=10) print(Sizes) # 👉️ <enum 'Sizes'> print(Sizes.SMALL.name) # 👉️ SMALL print(Sizes.SMALL.value) # 👉️ 10 print(Sizes.MEDIUM.name) # 👉️ MEDIUM print(Sizes.MEDIUM.value) # 👉️ 11