0% completed
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.
In this example, we will explore how to define and use a simple Enum in Python.
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 values can also be used in enums to make the code even more readable.
In this example, we will define an Enum using string values.
Explanation:
State.NEW, State.RUNNING, etc., are enum members with string values.State.NEW prints the enum representation showing both the name and the value.It's possible to iterate through all members of an enum, which is useful for listing or comparing all possible states or configurations.
In this example, we will iterate through the Color enum to display all its members.
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.The @unique decorator ensures all values in the enum are distinct, preventing duplicate values for different members.
In this example, we use the @unique decorator to enforce uniqueness in the enum values.
Explanation:
@unique: Ensures no two enum members have the same value.class Status(Enum): Defines an enum with unique status values.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.
.....
.....
.....