Ebooks

Python enum tutorial

Python enum tutorial shows how to work with enumerations in Python. Enumeration is a new data type introduced in Python 3.4.

Python enum

An enumeration is a set of symbolic names bound to unique, constant values. Enumerations can be used to create simple custom data types which include things such as seasons, weeks, types of weapons in a game, planets, grades, or days. By convention, enumeration names begin with an uppercase letter and are singular.

The enum module is used for creating enumerations in Python. Enumerations are created with the class keyword or with the functional API.

There are specific derived enumerations enum.IntEnum, enum.IntFlag, and enum.Flag.

Python enum simple example

The following is a simple example of a Python enumeration.

simple.py
#!/usr/bin/python3

from enum import Enum


class Season(Enum):
    SPRING = 1
    SUMMER = 2
    AUTUMN = 3
    WINTER = 4


seas = Season.SPRING
print(seas)

if seas == Season.SPRING:
    print("Spring")

print(list(Season))

In the example, we have a Season enumeration which has four distinct values: SPRING, SUMMER, AUTUMN, and WINTER. To access a member, we specify the enumeration name followed by a dot and the member name.

class Season(Enum):
    SPRING = 1
    SUMMER = 2
    AUTUMN = 3
    WINTER = 4

The Season enumeration is created with the class keyword. We inherit from the enum.Enum base class. We explicity set numbers to the enumeration values.

seas = Season.SPRING
print(seas)

An enumeration value is assigned to a variable and it is printed to the console.

if seas == Season.SPRING:
    print("Spring")

The Season.SPRING is used in an if expression.

print(list(Season))

With the list built-in function, we get the list of all possible values for the Season enum.

$ ./simple.py 
Season.SPRING
Spring
[<Season.SPRING: 1>, <Season.SUMMER: 2>, <Season.AUTUMN: 3>, <Season.WINTER: 4>]

This is the output.

Python enum simple example II

The next example presents some other basic functionality of a Python enum.

simple2.py
#!/usr/bin/python3

from enum import Enum


class Season(Enum):
    SPRING = 1
    SUMMER = 2
    AUTUMN = 3
    WINTER = 4


seas = Season.SPRING

print(seas)
print(isinstance(seas, Season))
print(type(seas))
print(repr(seas))

print(Season['SPRING'])
print(Season(1))

Again, we deal with a Season enumeration created with the class.

print(seas)

Here we print a human readable string representation of a Season member.

print(isinstance(seas, Season))

With the isinstance method, we check if the variable has a value of Season type.

print(type(seas))

The type function prints the type of the variable.

print(repr(seas))

The repr function provides more information about the enum.

print(Season['SPRING'])
print(Season(1))

Member of an enumeration can be accessed by item name and index.

$ ./simple2.py 
Season.SPRING
True
<enum 'Season'>
<Season.SPRING: 1>
Season.SPRING
Season.SPRING

This is the output.

Python enum functional creation

Python enums can be created with functional API.

functional.py
#!/usr/bin/python3

from enum import Enum

Season = Enum('Season', 'SPRING SUMMER AUTUMN WINTER', start=1)

seas = Season.SUMMER
print(seas)

if seas == Season.SUMMER:
    print("Summer")

There are several ways how we can specify the values with functional API. In later examples, we will use other functional ways.

Season = Enum('Season', 'SPRING SUMMER AUTUMN WINTER', start=1)

Here the values are specified in a string, separated by space. The start provides the initial value.

$ ./functional.py 
Season.SUMMER
Summer

This is the output.

Python enum iteration

We can iterate over Python enums.

iteration.py
#!/usr/bin/python3

from enum import Enum


Season = Enum('Season', ['SPRING', 'SUMMER', 'AUTUMN', 'WINTER'], start=5)

for season in Season:
    print(season)

for season in Season:
    print(season.name, season.value)

In this example, we create a Season enum where the values are set in a list of strings.

for season in Season:
    print(season)

We iterate over enum members in a for loop.

for season in Season:
    print(season.name, season.value)

Here we print their names and values.

$ ./iteration.py 
Season.SPRING
Season.SUMMER
Season.AUTUMN
Season.WINTER
SPRING 5
SUMMER 6
AUTUMN 7
WINTER 8

This is the output.

Python enum automatic values

Python enum values can be automatically set with the auto function.

automatic.py
#!/usr/bin/python3

from enum import Enum, auto


class Season(Enum):
    SPRING = auto()
    SUMMER = auto()
    AUTUMN = auto()
    WINTER = auto()


for season in Season:
    print(season.value)

We have a Season enum where its members get a value with auto function.

$ ./automatic.py 
1
2
3
4

This is the output.

Python enum unique member values

The member values of a Python enum can be enforced to be unique with the @unique decorator.

unique.py
#!/usr/bin/python3

from enum import Enum, unique

@unique
class Season(Enum):
    SPRING = 1
    SUMMER = 2
    AUTUMN = 3
    WINTER = 3
    # WINTER = 4


for season in Season:
    print(season)

The example fails with the ValueError: duplicate values found in <enum 'Season'>: WINTER -> AUTUMN error, because the AUTUMN and WINTER members have the same value. If we comment out the @unique decorator, the example prints three members; the WINTER is ignored.

Python enum __members__

The special attribute __members__ is a read-only ordered mapping of names to members.

members.py
#!/usr/bin/python3

from enum import Enum


Season = Enum('Season', [('SPRING', 1), ('SUMMER', 2), 
    ('AUTUMN', 3), ('WINTER', 4)])


for name, member in Season.__members__.items():
    print(name, member)

In the example, we use the __members__ property. The enumeration members are created with a list of tuples using functional API.

$ ./members.py 
SPRING Season.SPRING
SUMMER Season.SUMMER
AUTUMN Season.AUTUMN
WINTER Season.WINTER

This is the output.

Python enum.Flag

The enum.Flag is a base class for creating enumerated constants that can be combined using the bitwise operations without losing their Flag membership.

derived.py
#!/usr/bin/python3

from enum import Flag, auto


class Perm(Flag):
    EXECUTE = auto()
    WRITE = auto()
    READ = auto()


print(list(Perm))
print(Perm.READ | Perm.WRITE)

The example shows how the Flag can be used on permissions.

$ ./derived.py 
[<Perm.EXECUTE: 1>, <Perm.WRITE: 2>, <Perm.READ: 4>]
Perm.READ|WRITE

This is the output.

In this tutorial, we have worked with Python enumerations.

List all Python tutorials.