Enums in Python

by Alex
Enums in Python

This tutorial tells you how to work with enums in Python. Enum is a new data type introduced in Python 3.4.

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.
#!/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))
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.
class Weapon(Enum):
SWORD = 1
BOW = 2
DAGGER = 3
CLUB = 4
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.
ranged_weapon = Weapon.BOW
print(ranged_weapon)
Here a symbolic constant is assigned to the variable and printed to the console.
if ranged_weapon == Weapon.BOW:
print("It's a bow")
This fragment demonstrates the use of Weapon.BOW in an if statement.
print(list(Weapon))
With the built-in list function we get a list of all possible values for the Weapon enumeration. Output:
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.
#!/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))
Once again we are dealing with the enum Weapon, created using a class.
print(weapon)
Here we print a human-readable string representation of one of the enumeration members.
print(isinstance(weapon, Weapon))
We use the isinstance method to check if a variable is of type Weapon.
print(type(weapon))
The type function prints the type of the variable.
print(repr(weapon))
The repr function provides additional information about the enumeration.
print(Weapon['SWORD'])
print(Weapon(1))
A symbolic constant can be accessed by either its name or its value (index). Conclusion:
Weapon.SWORD
True
Weapon.SWORD
Weapon.SWORD

Functional enum creation in Python

Python enums can also be created using the functional API.
from enum import Enum
Weapon = Enum('Weapon', 'SWORD BOW DAGGER CLUB', start=1)
weapon = Weapon.DAGGER
print(weapon)
if weapon == Weapon.DAGGER:
print("Dagger")
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.
Weapon = Enum('Weapon', 'SWORD BOW DAGGER CLUB', start=1)
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.DAGGER
Dagger

Iterating enum in Python

We can iterate over Python enums.
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 this example, we create a Weapon enumeration where character constants are specified as a list of strings.
for weapon in Weapon:
print(weapon)
In the code above, we iterate through the enumeration members in a for loop.
for weapon in Weapon:
print(weapon.name, weapon.value)
Here we print their names and values. Output:
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().
#!/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)
In this snippet we have created a Weapon enumeration, the members of which get values using the auto function. Conclusion:
1
2
3
4

Unique enum values in Python

Character constant values can be forced to be unique using the @unique decorator.
#!/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)
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.

Python enum __members__

The special attribute members is an ordered read-only mapping of names to enum character constants.
#!/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)
In this example we are using the members property. The enumeration members are defined by a tuple list using the functional API. Conclusion:
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.
#!/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)
The example above shows how a flag can be used to check or set permissions. Conclusion: [, , ]
Permission.WRITE|READ

Related Posts

LEAVE A COMMENT