Enumerations in Python

Enumerations in Python

This article explains enumerations in Python.

YouTube Video

Enumerations in Python

Python's enum is a special class for defining constants, enhancing readability and helping to prevent coding errors.

What is an Enum?

Enum (short for enumeration) is a class used to define a set of named constants. It is typically used to group related constants together. For example, it is suitable for representing colors, days of the week, or directions.

Why use Enum?

There are several reasons to use Enum.

  • Improved readability: Using named constants makes the code more intuitive.
  • Prevention of bugs: It prevents changes or misuse of constant values.
  • Grouping: It organizes related constants into a single class, representing structured data.

Basic usage of Enum

To use enum, import the enum module and define a class. The class should inherit from Enum and define the values you want to treat as constants.

Basic example of Enum

 1from enum import Enum
 2
 3class Color(Enum):
 4    RED = 1
 5    GREEN = 2
 6    BLUE = 3
 7
 8# Usage of Enum
 9print(Color.RED)        # Color.RED
10print(Color.RED.name)   # RED
11print(Color.RED.value)  # 1

In this example, we define an Enum class called Color with three values. Each name can be accessed via the name attribute, and its associated value can be accessed via the value attribute.

Comparing Enums

Enum members can be compared either by name or by value. You can use the is operator or the == operator to check identity and equality.

Comparison example

 1from enum import Enum
 2
 3class Direction(Enum):
 4    NORTH = 1
 5    SOUTH = 2
 6    EAST = 3
 7    WEST = 4
 8
 9# Equality comparison
10print(Direction.NORTH == Direction.SOUTH)  # False
11print(Direction.NORTH == Direction.NORTH)  # True
12
13# Identity comparison using is
14print(Direction.NORTH is Direction.SOUTH)  # False
15print(Direction.NORTH is Direction.NORTH)  # True

Here, comparisons of Enum using == and is are demonstrated. Enum is designed to properly compare objects with the same names and values.

Automatic value assignment with auto()

If you want to automatically assign values to Enum members, you can use enum.auto(). auto() lets Python automatically assign values, eliminating the need for manual specification by developers.

Example of auto()

 1from enum import Enum, auto
 2
 3class Animal(Enum):
 4    DOG = auto()
 5    CAT = auto()
 6    MOUSE = auto()
 7
 8# Check the values of Enum
 9print(Animal.DOG.value)    # 1
10print(Animal.CAT.value)    # 2
11print(Animal.MOUSE.value)  # 3

In this example, using auto() removes the need to explicitly specify values, making the code more concise.

Assigning multiple values to Enum members

Enum members can also hold multiple values, such as tuples. This allows each member to hold additional related information.

Example using tuples

 1from enum import Enum
 2
 3class Status(Enum):
 4    ACTIVE = (1, 'Active user')
 5    INACTIVE = (2, 'Inactive user')
 6    SUSPENDED = (3, 'Suspended user')
 7
 8# Accessing Enum members
 9print(Status.ACTIVE.name)    # ACTIVE
10print(Status.ACTIVE.value)   # (1, 'Active user')
11print(Status.ACTIVE.value[1])  # Active user

In this example, the members of the Status class have two values each, representing state and description. This is useful when you want to associate multiple pieces of information with an Enum member.

Using Enum as flags

Python's enum includes a Flag class that can be used like bit flags. Using Flag allows you to manage multiple states in combination.

Example of Flag

 1from enum import Flag, auto
 2
 3class Permission(Flag):
 4    READ = auto()
 5    WRITE = auto()
 6    EXECUTE = auto()
 7
 8# Combining flags
 9permission = Permission.READ | Permission.WRITE
10print(permission)                 # Permission.READ|WRITE
11print(Permission.EXECUTE in permission)  # False

In this example, bitwise operations are used to combine multiple permissions. Using Flag lets you manage multiple states succinctly.

Points to keep in mind when using Enum

Immutability of Enum

Enum members are immutable. Once defined, their names or values cannot be changed. This is an important characteristic to maintain consistency as constants.

1from enum import Enum
2
3class Days(Enum):
4    MONDAY = 1
5    TUESDAY = 2
6
7# Example of immutability
8# Days.MONDAY = 3  # AttributeError: Cannot reassign members.

Prohibition of duplicate members

Enum members must have unique names and values. Even when duplicate values are allowed, Python automatically prioritizes the first member.

Summary

Python's enum module is a highly useful tool for grouping sets of constants, improving readability, and maintaining code consistency. A variety of uses are possible, from basic usage to automatic value assignment using auto(), as well as utilization as bit flags.

Properly understanding and mastering enum can improve code quality and help prevent errors.

You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.

YouTube Video