Python From Beginner to Advanced

0% completed

Previous
Next
Python - Enums

Enums (Enumerations) in Python are a way of organizing sets of related constants under a single type. Using the Enum class from Python’s standard library enum module, developers can define immutable, unique sets of names and values, enhancing code readability and reliability.

Enums ensure that variable values are restricted to a predefined set of options, reducing errors and clarifying intent within the codebase.

Example: Enum Basics

In this example, we will explore how to define and use a simple Enum in Python.

Python3
Python3

. . . .

Explanation:

  • from enum import Enum: Imports the Enum class from the enum module.
  • class Color(Enum): Defines an enum named Color.
  • RED = 1, GREEN = 2, BLUE = 3: Enum members with assigned integer values.
  • print(Color.RED): Displays the enum member Color.RED.
  • .name and .value attributes provide the string name and the associated value of the enum member, respectively.

String-based Enum

String values can also be used in enums to make the code even more readable.

Example: String-based Enum

In this example, we will define an Enum using string values.

Python3
Python3

. . . .

Explanation:

  • State.NEW, State.RUNNING, etc., are enum members with string values.
  • Accessing State.NEW prints the enum representation showing both the name and the value.

Iterating Through Enum Members

It's possible to iterate through all members of an enum, which is useful for listing or comparing all possible states or configurations.

Example: Iterating Enums

In this example, we will iterate through the Color enum to display all its members.

Python3
Python3

. . . .

Explanation:

  • for color in Color:: Loops through each member of the Color enum.
  • print(f"{color.name} has the value {color.value}"): Prints the name and value of each enum member.

Enum with @unique Decorator

The @unique decorator ensures all values in the enum are distinct, preventing duplicate values for different members.

Example: Unique Enum

In this example, we use the @unique decorator to enforce uniqueness in the enum values.

Python3
Python3

. . . .

Explanation:

  • @unique: Ensures no two enum members have the same value.
  • class Status(Enum): Defines an enum with unique status values.
  • Trying to assign duplicate values will result in a ValueError at runtime.

Enums in Python offer a structured and robust way to manage related sets of constants under a single type, enhancing readability and maintainability of the code. They ensure that variables adhere to a predefined set of options, which helps prevent bugs related to improper values and improves the clarity of the codebase. By using enums, developers can define clear and meaningful names for sets of values, making the code easier to understand and safer to use.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next