Python Enum

enum is a module that provides an enum-like data type.


Classes

Enum

enum.Enum is a basic enum.

import enum

class Color(enum.Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

# alternatively...
Color = enum.Enum('Color', ['RED', 'GREEN', 'BLUE'])

Color.BLUE.name  #'BLUE'
Color.RED.value  #1

The auto function will set integer values incrementing from 1.


Flag

enum.Flag is an enum that supports bitwise operations. These operations return a enum.Flag value.

import enum

class Color(enum.Flag):
    RED = enum.auto()
    GREEN = enum.auto()
    BLUE = enum.auto()

purple = Color.RED | Color.BLUE
white = Color.RED | Color.GREEN | Color.BLUE

Color.GREEN in purple  #False
Color.GREEN in white   #True
purple in white        #True
white in purple        #False

The auto function will set sequential powers of two starting from 1.


IntEnum

enum.IntEnum is the same as enum.Enum but the values are always integers.

The auto function will set integer values incrementing from 1.


IntFlag

enum.IntFlag is the same as enum.Flag but the values can also behave like integers. If an integer operation is performed, an integer is returned.

If a bitwise operation is performed, the result may or may not be a enum.Flag.


ReprEnum

enum.ReprEnum is the same as enum.Enum except that calling str() is passed through. This can be useful for creating subclasses of enum.Enum.


StrEnum

enum.StrEnum is the same as enum.Enum but the values are always strings.

The auto function will set a value of the member's name pushed to lowercase.


Meta Classes

EnumType

enum.EnumType is the metaclass for all other enum-like classes.


Functions

Auto

Instead of providing a value to an enum member, the auto function can be provided. It causes incrementing values to be set for the members.

import enum

class People(enum.Enum):
    Me = enum.auto()
    You = enum.auto()


Decorators

@Unique

If a enum.Enum (or subclass) is decorated with @unique, the members are inspected for duplicated values. A ValueError will be raised at runtime.


@Verify

If a enum.Enum (or subclass) is decorated with @verify, the members are inspected for some behavior. See the constants below for options.


Constants

Fittingly, the constants of enum are stored in enums.

These constants are used for verify.

Constants

Meaning

CONTINUOUS

NAMED_FLAGS

UNIQUE

These constants are used for configuring enum.IntFlag behavior.

Constants

Meaning

CONFIRM

EJECT

KEEP

STRICT


See also

Python enum module documentation

Python Module of the Day article for enum


CategoryRicottone

Python/Enum (last edited 2023-06-15 20:56:46 by DominicRicottone)