This tutorial tells you how to work with enums in Python. Enum is a new data type introduced in Python 3.4.
Table of Contents
Enum in Python
Enums are sets of symbolic names associated with unique constant values. They are used to create simple custom data types, such as seasons, weeks, game weapons, planets, scores, or days. By convention, enum names begin with a capital letter and are used in the singular. The enum module is used to create enumerations in Python. You can define them using the class keyword or the functional API. There are special derived enums enum.IntEnum, enum.IntFlag and enum.Flag.
A simple example of using enum in Python
Below is a simple example of Python code using enums.
In this example, we have an enum Weapon that has four different values: SWORD, BOW, DAGGER, and CLUB. To access one of the enum members, we have to specify the name of the enum followed by a dot and the name of the symbolic constant we’re interested in.
#!/usr/bin/python3
from enum import Enum
class Weapon(Enum):
SWORD = 1
BOW = 2
DAGGER = 3
CLUB = 4
ranged_weapon = Weapon.BOW
print(ranged_weapon)
if ranged_weapon == Weapon.BOW:
print("It's a bow")
print(list(Weapon))
Weapon enumeration is created by us using the class keyword, i.e. it is inherited from the base class enum.Enum. After that we explicitly set numbers corresponding to enum values.
class Weapon(Enum):
SWORD = 1
BOW = 2
DAGGER = 3
CLUB = 4
Here a symbolic constant is assigned to the variable and printed to the console.
ranged_weapon = Weapon.BOW
print(ranged_weapon)
This fragment demonstrates the use of Weapon.BOW in an if statement.
if ranged_weapon == Weapon.BOW:
print("It's a bow")
With the built-in list function we get a list of all possible values for the Weapon enumeration. Output:
print(list(Weapon))
Weapon.BOW
It's a bow
[, , , ]
Another example of using enum in Python
The following example introduces another part of the basic enum functionality in Python.
Once again we are dealing with the enum Weapon, created using a class.
#!/usr/bin/python3
from enum import Enum
class Weapon(Enum):
SWORD = 1
BOW = 2
DAGGER = 3
CLUB = 4
weapon = Weapon.SWORD
print(weapon)
print(isinstance(weapon, Weapon))
print(type(weapon))
print(repr(weapon))
print(Weapon['SWORD'])
print(Weapon(1))
Here we print a human-readable string representation of one of the enumeration members.
print(weapon)
We use the isinstance method to check if a variable is of type Weapon.
print(isinstance(weapon, Weapon))
The type function prints the type of the variable.
print(type(weapon))
The repr function provides additional information about the enumeration.
print(repr(weapon))
A symbolic constant can be accessed by either its name or its value (index). Conclusion:
print(Weapon['SWORD'])
print(Weapon(1))
Weapon.SWORD
True
Weapon.SWORD
Weapon.SWORD
Functional enum creation in Python
Python enums can also be created using the functional API.
There are several ways we can specify values using the functional API. In the examples that follow, we’ll apply different ways of specifying them.
from enum import Enum
Weapon = Enum('Weapon', 'SWORD BOW DAGGER CLUB', start=1)
weapon = Weapon.DAGGER
print(weapon)
if weapon == Weapon.DAGGER:
print("Dagger")
Here the names of symbolic constants are specified in a string, separated by spaces. The number passed in start defines the beginning of numbering of values for enum members. Output:
Weapon = Enum('Weapon', 'SWORD BOW DAGGER CLUB', start=1)
Weapon.DAGGER
Dagger
Iterating enum in Python
We can iterate over Python enums.
In this example, we create a Weapon enumeration where character constants are specified as a list of strings.
from enum import Enum
Weapon = Enum('Weapon', 'SWORD BOW DAGGER CLUB', start=10)
for weapon in Weapon:
print(weapon)
for weapon in Weapon:
print(weapon.name, weapon.value)
In the code above, we iterate through the enumeration members in a for loop.
for weapon in Weapon:
print(weapon)
Here we print their names and values. Output:
for weapon in Weapon:
print(weapon.name, weapon.value)
Weapon.SWORD
Weapon.BOW
Weapon.DAGGER
Weapon.CLUB
SWORD 10
BOW 11
DAGGER 12
CLUB 13
Automatically assigning names to enum in Python
The values of character constants can be automatically set with auto().
In this snippet we have created a Weapon enumeration, the members of which get values using the auto function. Conclusion:
#!/usr/bin/python3
from enum import Enum, auto
class Weapon(Enum):
SWORD = auto()
BOW = auto()
DAGGER = auto()
CLUB = auto()
for weapon in Weapon:
print(weapon.value)
1
2
3
4
Unique enum values in Python
Character constant values can be forced to be unique using the @unique decorator.
This example terminates with ValueError: duplicate values found in : CLUB -> DAGGER, because the members CLUB and DAGGER have the same value. If we comment out the @unique decorator, the example outputs three members; CLUB is ignored.
#!/usr/bin/python3
from enum import Enum, unique
@unique
class Weapon(Enum):
SWORD = 1
BOW = 2
DAGGER = 3
CLUB = 3
# CLUB = 4
for weapon in Weapon:
print(weapon)
Python enum __members__
The special attribute members is an ordered read-only mapping of names to enum character constants.
In this example we are using the members property. The enumeration members are defined by a tuple list using the functional API. Conclusion:
#!/usr/bin/python3
from enum import Enum
Weapon = Enum('Weapon', [('SWORD', 1), ('BOW', 2),
('DAGGER', 3), ('CLUB', 4)])
for name, member in Weapon.__members__.items():
print(name, member)
SWORD Weapon.SWORD
BOW Weapon.BOW
DAGGER Weapon.DAGGER
CLUB Weapon.CLUB
enum.Flag
Enum.Flag is a base class for creating numbered constants that can be combined using bitwise operations without losing their Flag membership.
The example above shows how a flag can be used to check or set permissions. Conclusion:
#!/usr/bin/python3
from enum import Flag, auto
class Permission(Flag):
READ = auto()
WRITE = auto()
EXECUTE = auto()
print(list(Permission))
print(Permission.READ | Permission.WRITE)
[, , ]
Permission.WRITE|READ