enum

What is an Enumeration?

An enumeration, or "enum" for short, is a way of representing a set of related items or categories using unique names. Enums are often used to represent constants or fixed values that cannot be changed during the execution of a program.

Creating Enums using the Enum Class:

  • We can create an enum using the Enum class from the enum module.

  • An enumeration with several members can be created.

  • Enum members are defined as constants using the class syntax similar to declaring a class.

from enum import Enum

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

Accessing Enum Members:

  • We can access enumeration members by their names.

  • We can iterate over all members of an enumeration using a for loop.

print(Color.RED)
# Output: <Color.RED: 1>

for color in Color:
    print(color)
# Output:
# <Color.RED: 1>
# <Color.GREEN: 2>
# <Color.BLUE: 3>

Using Enum Members:

  • Enum members are immutable (cannot be changed).

  • Enum members can be compared using the == and != operators.

  • Enum members can also be used in any place where a value of the enumeration's type is expected.

if Color.RED == Color(1):
    print("The colors are the same")

Real World Applications:

Enums are used in many real-world applications, such as:

  • Defining the different colors in a graphical user interface (GUI).

  • Representing the different states of a system or process.

  • Defining the different options in a menu or list.

Creating Enums using Function Call Syntax:

  • We can also create enums using the Enum class directly.

  • This can be useful when creating enums dynamically or from other data sources.

Color = Enum('Color', ['RED', 'GREEN', 'BLUE'])

Functional Syntax vs Class Syntax:

  • The functional syntax is more concise and can be useful when creating enums dynamically.

  • The class syntax is more extensible and allows for more control over the enumeration's behavior.

Other Types of Enums:

  • In addition to the basic Enum class, the enum module also provides several other types of enums:

    • IntEnum: Enums whose members are subclasses of int.

    • StrEnum: Enums whose members are subclasses of str.

    • Flag: Enums whose members can be combined using bitwise operations.

    • IntFlag: Enums whose members are subclasses of int and can be combined using bitwise operations.

Enum Decorators:

  • unique: Ensures that only one name is bound to any one value in the enum.

  • verify: Checks user-selectable constraints on an enumeration.


EnumType Metaclass

The EnumType metaclass is responsible for creating the enum class and its members based on the provided definitions. It handles tasks such as:

Setting Special Methods

  • __repr__: Provides a human-readable string representation of the enum member.

  • __str__: Returns the name of the enum member as a string.

  • __format__: Allows the enum member to be formatted using the str.format() method.

  • __reduce__: Used by Python's serialization protocol to safely recreate the enum member.

Creating Enum Members

The EnumType metaclass creates enum members by iterating over the provided definitions and doing the following:

  1. Verifying that the names are unique within the enum class.

  2. Creating instances of the enum member class (IntEnum or Enum) and assigning them to the enum class as attributes.

Handling Duplicates

If duplicate names are detected during member creation, an exception is raised. This ensures that enum members have unique identities.

Iteration

The EnumType metaclass allows iteration over the enum class to access its members in order.

Subclassing EnumType

It is possible to subclass EnumType to create custom enum classes with specialized behaviors. For example, you could create an enum class that automatically assigns numeric values to its members.

Code Example

class MyEnum(EnumType):
    A = 1
    B = 2
    C = 3

# Iterate over the enum members
for member in MyEnum:
    print(member, member.value)

# Access a specific enum member by name
print(MyEnum.A)

Real-World Applications

Enums are useful in many real-world scenarios, such as:

  • Representing choices or options within a system (e.g., file permissions, HTTP status codes).

  • Creating constants that represent different states or conditions (e.g., user roles, payment statuses).

  • Improving code readability and maintainability by using meaningful names instead of numeric values.

  • Controlling the order of items in a menu, list, or other collection.


What is an enum?

An enum is a way to represent a set of related values in a consistent and structured way. For example, you might have an enum to represent the different colors of a traffic light. The enum would have three members: RED, YELLOW, and GREEN. Each member would have a unique value, and you could use those values to represent the state of a traffic light.

How to create an enum

To create an enum, you use the enum.Enum class. The following code creates an enum to represent the colors of a traffic light:

from enum import Enum

class TrafficLightColor(Enum):
    RED = 1
    YELLOW = 2
    GREEN = 3

The TrafficLightColor enum has three members: RED, YELLOW, and GREEN. Each member has a unique value, which is stored in the value attribute. You can access the value of a member using the value attribute.

print(TrafficLightColor.RED.value)  # prints 1

How to use an enum

You can use an enum to represent the state of an object. For example, you could use the TrafficLightColor enum to represent the state of a traffic light.

traffic_light = TrafficLightColor.RED

You can also use an enum to make decisions. For example, you could use the TrafficLightColor enum to decide what to do when you approach a traffic light.

def what_to_do(color):
    if color == TrafficLightColor.RED:
        print("Stop")
    elif color == TrafficLightColor.YELLOW:
        print("Caution")
    elif color == TrafficLightColor.GREEN:
        print("Go")

Real-world applications of enums

Enums are used in a variety of real-world applications, including:

  • Representing the states of objects (e.g., the state of a traffic light, the state of a button)

  • Representing the values of settings (e.g., the font size of a text box, the color of a background)

  • Representing the values of constants (e.g., the value of pi, the value of the speed of light)

Improved code snippets

The following code snippet shows how to use an enum to create a drop-down list of options in a web application.

from enum import Enum
from flask import Flask, render_template

app = Flask(__name__)

class Fruit(Enum):
    APPLE = 1
    ORANGE = 2
    BANANA = 3

@app.route("/")
def index():
    return render_template("index.html", fruits=Fruit)

if __name__ == "__main__":
    app.run()

The following HTML template is used to render the drop-down list.

<!DOCTYPE html>
<html>
  <body>
    <h1>Choose a fruit:</h1>
    <select>
      <div data-gb-custom-block data-tag="for">

      <option value="{{ fruit.value }}">{{ fruit.name }}</option>
      

</div>
    </select>
  </body>
</html>

When a user selects a fruit from the drop-down list, the value of the selected fruit is sent to the server. The server can then use the value to make a decision, such as displaying information about the selected fruit.


EnumType.contains() Method

Explanation:

This method checks if a given value is a member of the Enum type. It returns True if the value is a member, and False otherwise.

Example:

from enum import Enum

class Color(Enum):
    RED = "red"
    GREEN = "green"
    BLUE = "blue"

color = Color.RED

if color in Color:
    print("The color is a valid member of the Color Enum.")

Output:

The color is a valid member of the Color Enum.

Real-World Applications:

  • Validating user input to ensure that it matches a defined set of values.

  • Creating menus or options that only allow users to choose from a specific list of choices.

  • Managing states or configurations in a system where only a limited set of values is allowed.

Additional Notes:

  • In Python versions 3.12 and earlier, attempting to check for a non-Enum member would raise a TypeError. In Python 3.12 and later, it simply returns False.

  • The contains() method can be used both for the Enum class itself and for individual Enum members.


**dir** method for enum.Enum class in Python returns a list of attributes and members of the enumeration.

  • dir(Color) returns ['BLUE', 'GREEN', 'RED', 'class', 'contains', 'doc', 'getitem', 'init_subclass', 'iter', 'len', 'members', 'module', 'name', 'qualname']

Example:

from enum import Enum

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

print(dir(Color))
# Output: ['BLUE', 'GREEN', 'RED', '__class__', '__contains__', '__doc__', '__getitem__', '__init_subclass__', '__iter__', '__len__', '__members__', '__module__', '__name__', '__qualname__']

Enum getitem explained

The __getitem__ method of an Enum class allows you to access an enum member by its name.

For example, consider the following enum:

from enum import Enum

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

You can access the BLUE member of the Color enum using the following syntax:

Color['BLUE']

This will return the BLUE enum member, which has a value of 3:

<Color.BLUE: 3>

You can also use the __getitem__ method to access enum members by their value:

Color[3]

This will also return the BLUE enum member.

If you try to access an enum member that does not exist, a KeyError will be raised:

Color['PURPLE']

Real-world applications

Enums are useful in a variety of real-world applications. For example, you can use enums to represent:

  • The different states of a finite state machine

  • The different options in a menu

  • The different types of errors that can occur in a program

Enums make it easier to read and write code by providing a clear and concise way to represent a set of related values.

Improved code snippets

Here is an improved example of using the __getitem__ method to access an enum member by its name:

from enum import Enum

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

color = Color['BLUE']

print(color)  # prints <Color.BLUE: 3>

Here is an improved example of using the __getitem__ method to access an enum member by its value:

from enum import Enum

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

color = Color[3]

print(color)  # prints <Color.BLUE: 3>

Enum Type Iterator

Simplified Explanation:

Imagine an Enum type as a collection of choices, like colors. Each choice has a name (e.g., "RED") and a value (e.g., 1). The __iter__ method allows you to loop through all these choices in the order they were defined.

Code Snippet:

from enum import Enum

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

for color in Color:
    print(color)

Output:

<Color.RED: 1>
<Color.GREEN: 2>
<Color.BLUE: 3>

Detailed Explanation:

  • The __iter__ method is a built-in method for Enum types.

  • It returns an iterator that generates each member of the enum in the order they were defined.

  • The iterator is an object that can be used in a for loop to iterate through the members.

  • Each iteration returns a tuple containing the member's name and value.

  • In the code snippet, we have an Enum type called Color with three members: RED, GREEN, and BLUE.

  • The for loop iterates through the members of Color and prints their names and values.

Real-World Applications:

  • Iterating through the choices in an enum type can be useful for displaying options to a user or for processing data based on different choices.

  • For example, consider a game where players can choose between different weapons. You could use an Enum type to represent the weapons and then iterate through them to display them in a menu.


What is an Enum Type?

An enum type (short for "enumeration") is a special type of variable that can only take on a limited number of predefined values. For example, you could have an enum type called Color that can only take on the values RED, GREEN, and BLUE.

Counting the Number of Members in an Enum Type

The __len__ method returns the number of members in an enum type. For example, if you have the following enum type:

from enum import Enum

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

You can get the number of members in this enum type using the following code:

>>> len(Color)
3

Real-World Applications of Enum Types

Enum types are often used to represent a set of fixed values that are related to each other. For example, you could use an enum type to represent the status of an order:

from enum import Enum

class OrderStatus(Enum):
    PENDING = 1
    SHIPPED = 2
    DELIVERED = 3

This enum type could then be used in the following code:

order_status = OrderStatus.PENDING

if order_status == OrderStatus.PENDING:
    print("The order is still being processed.")
elif order_status == OrderStatus.SHIPPED:
    print("The order has been shipped.")
elif order_status == OrderStatus.DELIVERED:
    print("The order has been delivered.")

Benefits of Using Enum Types

Using enum types has several benefits:

  • They make your code more readable and maintainable.

  • They prevent you from using invalid values.

  • They can be used to create more expressive and error-resistant code.


**Attribute: EnumType.**members****

Simplified Explanation:

The __members__ attribute of an enum class returns a dictionary that contains all the members of the enum class. Each key in the dictionary is the name of an enum member, and the corresponding value is the enum member itself.

Real-World Example:

Consider the following enum class:

from enum import Enum

class Colors(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

The __members__ attribute of the Colors enum class will be:

{
    "RED": Colors.RED,
    "GREEN": Colors.GREEN,
    "BLUE": Colors.BLUE
}

Potential Applications:

  • Iterate over all the members of an enum class.

  • Get the value associated with a particular enum member by name.

  • Check if a particular value is a member of an enum class.


EnumType.reversed(cls)

What is it?

The EnumType.__reversed__ method in Python's enum module returns each member in the enum in reverse definition order.

How to use it?

To use the EnumType.__reversed__ method, simply call it on the enum class. For example:

>>> from enum import Enum

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

>>> list(reversed(Color))
[<Color.BLUE: 3>, <Color.GREEN: 2>, <Color.RED: 1>]

Real-World Example

The EnumType.__reversed__ method can be used to iterate over the members of an enum in reverse order. This can be useful for displaying the members in a user interface or for performing other operations that require the members to be in reverse order.

Potential Applications

The EnumType.__reversed__ method can be used in a variety of real-world applications, including:

  • Displaying the members of an enum in a user interface

  • Performing other operations that require the members of an enum to be in reverse order

  • Testing the order of the members of an enum

Improved Code Snippets

The following code snippet shows how to use the EnumType.__reversed__ method to display the members of an enum in reverse order:

from enum import Enum

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

for color in reversed(Color):
    print(color)

Output:

<Color.BLUE: 3>
<Color.GREEN: 2>
<Color.RED: 1>

Enum Alias

An enum alias is an additional name that can be used to refer to an existing value in an enum. For example, you can define an enum like this:

from enum import Enum

class Colors(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

This enum has three values: RED, GREEN, and BLUE. However, you can also define aliases for these values, like this:

Colors._add_alias_('primary', Colors.RED)
Colors._add_alias_('secondary', Colors.GREEN)
Colors._add_alias_('tertiary', Colors.BLUE)

Now, you can refer to the values in the enum using either their original names or their aliases. For example:

print(Colors.RED)  # prints 'RED'
print(Colors['primary'])  # also prints 'RED'

Adding aliases to enums can be useful for making your code more readable and maintainable. For example, if you have a function that takes a color as an argument, you can use an alias to make it clear which color you want to pass to the function.

def print_color(color):
    print(color)

print_color(Colors.RED)  # prints 'RED'
print_color(Colors['primary'])  # also prints 'RED'

Real-World Applications

Enum aliases can be used in a variety of real-world applications, including:

  • User interfaces: Aliases can be used to provide more user-friendly names for enum values. For example, you could define an enum for the status of a task:

class TaskStatus(Enum):
    NEW = 1
    IN_PROGRESS = 2
    COMPLETED = 3

Then, you could add aliases to make the status values more user-friendly:

TaskStatus._add_alias_('not_started', TaskStatus.NEW)
TaskStatus._add_alias_('working_on_it', TaskStatus.IN_PROGRESS)
TaskStatus._add_alias_('done', TaskStatus.COMPLETED)

Now, you could display the status of a task to a user like this:

task_status = TaskStatus.NEW
print(task_status)  # prints 'NEW'
print(task_status.name)  # prints 'not_started'
  • Configuration files: Aliases can be used to make configuration files more readable and maintainable. For example, you could define an enum for the different levels of logging:

class LogLevel(Enum):
    DEBUG = 10
    INFO = 20
    WARNING = 30
    ERROR = 40
    CRITICAL = 50

Then, you could add aliases to make the log level values more readable:

LogLevel._add_alias_('debug', LogLevel.DEBUG)
LogLevel._add_alias_('info', LogLevel.INFO)
LogLevel._add_alias_('warning', LogLevel.WARNING)
LogLevel._add_alias_('error', LogLevel.ERROR)
LogLevel._add_alias_('critical', LogLevel.CRITICAL)

Now, you could set the log level in a configuration file like this:

[logging]
level = debug

This would be more readable than setting the log level to the numeric value 10.


EnumType.add_value_alias

Explanation

The EnumType class in python's enum module allows you to create your own enumerated types. An enumerated type is a set of named values that represent different options or choices.

The _add_value_alias_ method of the EnumType class allows you to add an alias to an existing value in the enumerated type. This means that you can use another name to refer to the same value.

For example, let's say you have an enumerated type called Colors that has the following values:

from enum import Enum

class Colors(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

You can add an alias to the RED value using the _add_value_alias_ method:

Colors._add_value_alias_('SCARLET', Colors.RED)

Now you can use either Colors.RED or Colors.SCARLET to refer to the same value.

Real-World Example

One potential application of using aliases in enumerated types is to provide more descriptive or user-friendly names for certain values. For example, in the Colors enumerated type, you could add an alias called STOP to the RED value:

Colors._add_value_alias_('STOP', Colors.RED)

This would allow you to use Colors.STOP instead of Colors.RED when you want to refer to the color that represents the stop sign.

Complete Code Implementation

Here is a complete code implementation of adding an alias to an existing value in an enumerated type:

from enum import Enum

class Colors(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

Colors._add_value_alias_('SCARLET', Colors.RED)

print(Colors.RED)  # Output: <Colors.RED: 1>
print(Colors.SCARLET)  # Output: <Colors.RED: 1>

In this example, the SCARLET alias is added to the RED value in the Colors enumerated type. You can then use either Colors.RED or Colors.SCARLET to refer to the same value.


What is an Enum?

An enum is a special type of variable that can only take on a limited set of values. These values are typically defined as constants, which are simply unchanging names for specific values.

Creating an Enum

To create an enum in Python, you use the Enum class. Here's an example:

from enum import Enum

class Colors(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

This code creates an enum called Colors with three constants: RED, GREEN, and BLUE. Each constant is assigned a unique value (1, 2, and 3).

Using an Enum

You can use an enum constant in your code by simply using its name. For example:

color = Colors.RED
print(color)  # Output: RED

You can also iterate over the enum constants:

for color in Colors:
    print(color)  # Output: RED, GREEN, BLUE

Applications of Enums

Enums have a variety of applications in real-world programming, including:

  • Representing states or options in a program

  • Defining error codes

  • Creating type-safe constants

Example: Representing States

Imagine you have a program that controls a traffic light. You could use an enum to represent the different states of the light:

from enum import Enum

class TrafficLight(Enum):
    RED = 1
    YELLOW = 2
    GREEN = 3

In your code, you could then use the enum constants to set the state of the light:

traffic_light = TrafficLight.RED
# ...
traffic_light = TrafficLight.YELLOW
# ...
traffic_light = TrafficLight.GREEN

This ensures that the state of the light is always one of the valid options (RED, YELLOW, or GREEN).


Enum.name

What is it?

Enum.name is an attribute of an enum member that returns the name of the member as a string.

How to use it:

To access the name of an enum member, simply use the dot notation like this:

>>> Color.BLUE.name
'BLUE'

Real-world example:

Suppose you have an enum representing the colors of the rainbow:

from enum import Enum

class Color(Enum):
    RED = 1
    ORANGE = 2
    YELLOW = 3
    GREEN = 4
    BLUE = 5
    INDIGO = 6
    VIOLET = 7

You can use the Enum.name attribute to get the name of each color:

>>> Color.RED.name
'RED'
>>> Color.BLUE.name
'BLUE'

Potential applications:

The Enum.name attribute can be useful for displaying the names of enum members in user interfaces, logs, or other places where you need to represent the enum values as strings.


What is an Enum?

An Enum is a special type of variable in Python that represents a set of fixed values. It's like a multiple choice question, where you can only choose from a certain number of options.

Creating an Enum

To create an enum, you use the enum class and a list of values for the options. For example:

from enum import Enum

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

This creates an enum called Color with three options: RED, GREEN, and BLUE. Each option is assigned a unique value (1, 2, and 3).

Using an Enum

You can use an enum like any other variable in Python. For example, you can check the value of an enum:

color = Color.RED
print(color.value)  # prints 1

You can also compare enums:

if color == Color.GREEN:
    print("The color is green")

Enum Member Values

The values given to enum members can be anything, such as integers, strings, or even other enums. If the exact value doesn't matter, you can use an auto placeholder. Python will automatically assign an appropriate value.

from enum import Enum, auto

class Sizes(Enum):
    SMALL = auto()
    MEDIUM = auto()
    LARGE = auto()

In this example, the values for SMALL, MEDIUM, and LARGE will be assigned automatically.

Potential Applications

Enums have many applications in real-world programming, such as:

  • Representing states in a finite state machine

  • Creating constants for different values

  • Defining options for user input

  • Enum types can be used to represent any kind of data that has a finite number of possible values, such as the status of a task (e.g., new, in progress, completed), the type of a file (e.g., text, image, video), or the direction of movement (e.g., up, down, left, right).

  • Enum types can make code more readable and maintainable, as they provide a clear and concise way to represent a set of possible values.

  • For example, in a game development scenario, you could create an enum to represent the different types of tiles in a game world, such as Grass, Water, Forest, and Mountain. This would allow you to easily identify and refer to different types of tiles in your code, rather than using hard-coded values or strings.

  • Enums are also helpful for ensuring that data is consistent and valid. For example, if you have a database table that represents the status of a task, you could create an enum to define the possible values for the status column. This would prevent invalid values from being stored in the database, such as 'foo' or 'bar', and would make it easier to enforce business rules.


Attribute: Enum.name

Simplified Explanation:

An enum member's "name" attribute stores the name of the member as a string. For example, if you have an enum called "Colors" with members "RED", "GREEN", and "BLUE", the "name" attribute for "RED" would be "RED".

Real-World Example:

from enum import Enum

class Colors(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

print(Colors.RED._name_)  # Output: 'RED'

Potential Applications:

  • Storing the name of an enum member for display purposes.

  • Comparing the names of enum members for equality.

Additional Notes:

  • The "name" attribute is a read-only property.

  • The "name" attribute is automatically generated based on the member's value.

  • The "name" attribute is used internally by the enum class for various operations.


What is an Enum?

An enum is a way to represent a set of related values, like the days of the week or the colors of the rainbow. Each value in an enum has a name and a unique number.

Creating an Enum

To create an enum, you use the enum module. For example, to create an enum representing the days of the week, you would write:

from enum import Enum

class Day(Enum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 7

This creates an enum class called Day with seven members: MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, and SUNDAY. Each member has a name and a unique number.

Using an Enum

You can use an enum by accessing its members. For example, to get the number associated with MONDAY, you would write:

Day.MONDAY.value

This would return the number 1.

You can also iterate over the members of an enum. For example, to iterate over the days of the week, you would write:

for day in Day:
    print(day)

This would print the following:

Day.MONDAY
Day.TUESDAY
Day.WEDNESDAY
Day.THURSDAY
Day.FRIDAY
Day.SATURDAY
Day.SUNDAY

Real-World Applications

Enums are used in a variety of real-world applications, including:

  • Representing the states of a finite state machine

  • Representing the options in a drop-down menu

  • Representing the values in a database table

Improved Code Example

Here is an improved version of the code example above:

from enum import Enum

class Day(Enum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 7

def get_day_name(day):
    """
    Returns the name of the given day.

    Args:
        day: A member of the Day enum.

    Returns:
        The name of the given day.
    """

    return day.name

def main():
    """
    Gets and prints the name of each day of the week.
    """

    for day in Day:
        print(get_day_name(day))

if __name__ == "__main__":
    main()

This code defines a function called get_day_name() that takes a member of the Day enum and returns its name. The main() function then gets and prints the name of each day of the week.


Enum.order Attribute

Simplified Explanation:

Imagine you're creating a list of fruits. You can list them in any order you want, like apples, bananas, oranges. But sometimes, you might want to sort them in a specific order, like alphabetical order. In Python's Enum module, Enum._order_ attribute used to help do this.

Detailed Explanation:

The Enum._order_ attribute was used to determine the order of members in an enum class. It could be set to True or False. When set to True, members would be ordered based on their creation order. When set to False, the order was not defined.

Code Snippet:

from enum import Enum

class Fruits(Enum):
    apples = 1
    bananas = 2
    oranges = 3

# Get the order of members
print(Fruits._order_)  # Output: False

Removal and Backward Compatibility:

The Enum._order_ attribute is no longer used in Python. It has been removed to simplify the enum class initialization process. However, it is still accessible for backward compatibility reasons and will be removed in a future version of Python.

Real-World Applications:

Enumerations are useful in several real-world applications, such as:

  • Representing a set of predefined choices or options, like fruit types or directions.

  • Ensuring that only valid values are used in a program, like ensuring that a month is represented as a value from 1 to 12.

  • Making code more readable and maintainable by using descriptive names instead of numeric values.

Improved Example:

from enum import Enum

class Directions(Enum):
    NORTH = 1
    EAST = 2
    SOUTH = 3
    WEST = 4

# Get the members in order of their creation
print(Directions.NORTH)  # Output: Directions.NORTH
print(Directions.EAST)  # Output: Directions.EAST
print(Directions.SOUTH)  # Output: Directions.SOUTH
print(Directions.WEST)  # Output: Directions.WEST

Enum.ignore

Explanation

When defining an enumeration, there may be some values that you don't want to include as members. Instead, you may want to use them for other purposes.

For example, you could have a TimePeriod enumeration with the following values:

from enum import Enum

class TimePeriod(Enum):
    DAY = 1
    WEEK = 2
    MONTH = 3
    QUARTER = 4
    YEAR = 5

However, you may want to have a convention where names that end with _IGNORE are ignored and not included as members. To achieve this, you can use the _ignore_ attribute when defining the enumeration:

from enum import Enum

class TimePeriod(Enum):
    _ignore_ = ["DAY_IGNORE", "WEEK_IGNORE"]  # These names will be ignored
    DAY = 1
    WEEK = 2
    MONTH = 3
    QUARTER = 4
    YEAR = 5

By doing this, the TimePeriod enumeration will only have the members DAY, WEEK, MONTH, QUARTER, and YEAR. The names DAY_IGNORE and WEEK_IGNORE will not be included as members.

Real-World Example

Let's say you have a system that tracks the status of orders. You could define an OrderStatus enumeration with the following values:

from enum import Enum

class OrderStatus(Enum):
    PENDING = 1
    PROCESSING = 2
    SHIPPED = 3
    DELIVERED = 4
    CANCELED = 5

However, you may also want to have a convention where names that end with _IGNORE are not displayed to the user. For example, you could have a function that displays the status of an order:

def display_order_status(order):
    if order.status in OrderStatus._ignore_:
        return "Unknown"
    return order.status.name

By using the _ignore_ attribute, you can create a consistent way to handle ignored values in your enumeration.


Enums (Enumerations)

In programming, enumerations are used to create a set of named constants. They are useful when you have a fixed number of options or values that you want to represent in your code.

The Enum Class

Python's Enum class provides an easy way to define and use enumerations.

Creating an Enum

To create an enumeration, you define a subclass of the Enum class and specify the names and values of the constants. For example:

from enum import Enum

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

This creates an Enum named Color with three members: RED, GREEN, and BLUE. Each member has a name and a value (the integer values are assigned by default).

Using an Enum

You can access the members of an Enum using the dot notation. For example:

print(Color.RED)  # Output: <Color.RED: 1>
print(Color.RED.name)  # Output: RED
print(Color.RED.value)  # Output: 1

Class Methods on Enums

Enums can have class methods, which are methods that are defined on the Enum class itself rather than on individual members. For example, you can define a today method on the Weekday Enum that prints the current weekday:

from datetime import date

class Weekday(Enum):
    MONDAY = 1
    TUESDAY = 2
    ...

    @classmethod
    def today(cls):
        print('Today is {}'.format(cls(date.today().isoweekday()).name))

Weekday.today()  # Output: Today is MONDAY

Real-World Applications

Enums are commonly used in various applications:

  • Status codes: HTTP status codes, for example, are defined as an Enum in the http module.

  • Error codes: Error codes thrown by an application can be defined as an Enum to provide clear and consistent error messages.

  • Options: Enums can be used to represent a set of options, such as the different types of actions a user can take in an application.

Benefits of Using Enums

  • Clarity: Enums make it easier to understand the meaning of constants in your code.

  • Type safety: Enums enforce type checking, ensuring that only valid values are used.

  • Extensibility: Adding new members to an Enum is straightforward and does not require modifying existing code.


Enum.generate_next_value

What is it?

_generate_next_value_ is a static method used to determine the next value returned by the auto() function when creating an Enum.

How does it work?

When you define an Enum member using auto(), the _generate_next_value_ method is called to generate the next value for that member.

By default, the _generate_next_value_ method returns the next sequential number starting from 1. However, you can override this method to define your own logic for generating values.

Why use it?

You can use _generate_next_value_ to create custom enumerations with non-sequential or non-integer values.

Example:

Let's create an Enum that represents the powers of three:

from enum import Enum, auto

class PowersOfThree(Enum):
    @staticmethod
    def _generate_next_value_(name, start, count, last_values):
        return 3 ** (count + 1)

    FIRST = auto()
    SECOND = auto()

In this example, we override the _generate_next_value_ method to return the next power of three.

The FIRST member will have the value 3 (3 ** 1), and the SECOND member will have the value 9 (3 ** 2).

Real-world applications:

You can use _generate_next_value_ to create enums that represent:

  • Custom flags or permissions

  • Error codes

  • Status codes

  • Any other type of enumeration where you need control over the values assigned to the members.


Enum is a built-in Python module that provides a way to define enumerated types. An enumerated type is a set of named constants, and each constant has a unique value. Enumerations are useful for representing a set of related values that can be used in a program. For example, you could define an enumeration to represent the days of the week:

from enum import Enum

class Weekday(Enum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 7

Once you have defined an enumeration, you can use the constants in your program. For example, you could use the Weekday enumeration to print the name of the current day of the week:

import datetime

today = datetime.datetime.today()
weekday = today.weekday()

print(Weekday(weekday).name)

Creating Enumerations

To create an enumeration, you use the Enum class. The Enum class takes a variable number of arguments, which are the names of the constants in the enumeration. The values of the constants are assigned automatically, starting from 1 and incrementing by 1 for each constant. You can also specify the values of the constants explicitly by passing them as keyword arguments to the Enum class.

Using Enumerations

Once you have created an enumeration, you can use the constants in your program. You can access the constants by their names, or you can use the value attribute to get the value of a constant. You can also use the name attribute to get the name of a constant.

Real-World Applications

Enumerations are used in a variety of real-world applications, including:

  • Representing the states of a finite state machine

  • Representing the different types of errors that can occur in a program

  • Representing the different options that are available to a user in a menu

Potential Applications

Here are some potential applications of enumerations in real-world code:

  • A game development framework could use enumerations to represent the different states of a game object, such as "idle", "moving", and "attacking".

  • A web application could use enumerations to represent the different types of user accounts, such as "admin", "moderator", and "user".

  • A data analysis application could use enumerations to represent the different types of data that is being analyzed, such as "numerical", "categorical", and "textual".


Method: Enum.__init_subclass__

Purpose: To customize subclasses of the Enum class.

Simplified Explanation:

Imagine you have a class called Fruit that represents different types of fruits. You can create subclasses of Fruit to represent specific fruits, like Apple, Orange, and Banana.

The Enum.__init_subclass__ method allows you to further configure how these subclasses behave. By default, it does nothing, but you can override it to add custom functionality.

Code Snippet:

class Fruit(Enum):
    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        cls.color = kwargs.get("color", "Unknown")

class Apple(Fruit, color="Red"):
    pass

class Orange(Fruit, color="Orange"):
    pass

Explanation:

In this code, we override the __init_subclass__ method for the Fruit class. When a new subclass is created (e.g., Apple or Orange), it will automatically inherit the color attribute from the class definition. If the subclass does not specify a color, it will default to "Unknown".

Real-World Applications:

  • You can use __init_subclass__ to set default values for attributes in subclasses.

  • You can use it to enforce certain constraints on subclasses, such as requiring them to have specific attributes or methods.

  • You can use it to add custom functionality to subclasses, such as additional methods or properties.


Enum is a powerful tool in Python that allows you to create your own custom types. It provides a way to represent a set of related values, similar to an enumeration in other programming languages. An enumeration, or enum, is a collection of named constants that represent a specific set of values. In Python, enums can be created using the enum module.

Enum._missing_ is a special method that is called when a value is not found in the enum. By default, it does nothing, but you can override it to implement custom search behavior. This can be useful if you want to support values that are not explicitly defined in the enum.

For example, let's say you have an enum that represents the different build types for a software project:

from enum import StrEnum

class Build(StrEnum):
    DEBUG = auto()
    OPTIMIZED = auto()

# Custom search behavior to handle lowercase values
@classmethod
def _missing_(cls, value):
    value = value.lower()
    for member in cls:
        if member.value == value:
            return member
    return None

With this custom search behavior, you can now use the enum to lookup values that are not explicitly defined:

>>> Build.DEBUG.value
'debug'
>>> Build('deBUG')
<Build.DEBUG: 'debug'>

Potential applications of enums in the real world:

  • Representing the different states of a system, such as RUNNING, STOPPED, or PAUSED.

  • Representing the different types of data that can be processed by a program, such as INTEGER, FLOAT, or STRING.

  • Representing the different options that can be passed to a function or method, such as ADD, SUBTRACT, or MULTIPLY.

Enums can be used whenever you need to represent a set of related values in a clear and concise way.


Enum.new Method

The Enum.__new__ method is a special method that is called when a new enum class is created. It takes a variable number of arguments and keyword arguments, which are used to initialize the new enum class.

By default, the Enum.__new__ method does not exist. However, it can be specified in the enum class definition or in a mixin class (such as int). If it is specified, all values given in the member assignment will be passed to the Enum.__new__ method.

For example, the following code defines an enum class called MyIntEnum that uses the int mixin class:

from enum import Enum

class MyIntEnum(Enum):
    SEVENTEEN = '1a', 16

The Enum.__new__ method for the MyIntEnum class will be called with the following arguments:

MyIntEnum.__new__(MyIntEnum, 'MyIntEnum', (), {'SEVENTEEN': ('1a', 16)})

The first argument is the enum class itself. The second argument is the name of the enum class. The third argument is an empty tuple, which represents the bases of the enum class. The fourth argument is a dictionary that contains the members of the enum class.

The Enum.__new__ method will use these arguments to create a new enum class. The new enum class will have the following members:

MyIntEnum.SEVENTEEN = '1a'

The value of the SEVENTEEN member is '1a'. This is because the int mixin class was used to create the MyIntEnum class. The int mixin class converts all values given in the member assignment to integers.

Real-World Example

Enum classes are often used to represent a fixed set of values. For example, the following code defines an enum class called Colors that represents the primary colors:

from enum import Enum

class Colors(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

The Colors enum class can be used to represent the color of an object. For example, the following code uses the Colors enum class to represent the color of a car:

class Car:
    def __init__(self, color):
        self.color = color

my_car = Car(Colors.RED)

The my_car object has a color of Colors.RED. This means that the car is red.

Potential Applications

Enum classes can be used in a variety of applications, including:

  • Representing a fixed set of values

  • Providing a way to easily compare values

  • Making code more readable and maintainable

Here are some specific examples of how enum classes can be used:

  • In a database, enum classes can be used to represent the different types of data that can be stored in a column.

  • In a web application, enum classes can be used to represent the different states that a user can be in.

  • In a programming language, enum classes can be used to represent the different types of errors that can occur.


Enum.repr

The __repr__ method is a special method that is called when the repr() function is used on an object. The repr() function returns a string representation of the object that can be used to recreate the object.

By default, the __repr__ method for an Enum value returns the name of the Enum class, followed by the name of the Enum member, and then the value of the Enum member. For example, the following code:

class MyEnum(Enum):
    A = 1
    B = 2
    C = 3

print(repr(MyEnum.A))

would print the following output:

MyEnum.A

You can override the __repr__ method to return a different string representation of the Enum value. For example, the following code overrides the __repr__ method to return the name of the Enum member only:

class MyEnum(Enum):
    A = 1
    B = 2
    C = 3

    def __repr__(self):
        return self.name

print(repr(MyEnum.A))

This would print the following output:

A

Real-world applications

The __repr__ method can be used to customize the way that Enum values are displayed in error messages, logs, and other places where the string representation of the Enum value is used.

For example, you could use the __repr__ method to add additional information to the string representation of the Enum value, such as the description of the Enum member. This could be useful for debugging purposes or for providing more information to users.

Code implementation

The following code shows how to implement the __repr__ method for an Enum:

class MyEnum(Enum):
    A = 1
    B = 2
    C = 3

    def __repr__(self):
        return f"{self.__class__.__name__}.{self.name} ({self.value})"

print(repr(MyEnum.A))

This would print the following output:

MyEnum.A (1)

Potential applications

The __repr__ method can be used for a variety of purposes, including:

  • Customizing the way that Enum values are displayed in error messages, logs, and other places where the string representation of the Enum value is used.

  • Adding additional information to the string representation of the Enum value, such as the description of the Enum member.

  • Providing more information to users about the meaning of the Enum value.


Enum Class

  • What is it?

    • An enumeration class in Python is a way to define a set of named constants.

  • How to create an enum class?

    • Use the Enum class as the base class for your custom enum class.

    • Define the members of your enum class as class attributes.

  • Example:

# Define an enum class for colors
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

str Method

  • What is it?

    • The __str__ method is a special method that is called when you convert an object to a string.

  • How to override the str method?

    • Define a __str__ method in your enum class and return the desired string representation.

  • Example:

# Override the __str__ method to return the enum name instead of the default
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

    def __str__(self):
        return self.name

Real World Applications

  • Representing states: Enumerations are useful for representing states in a program, such as the state of a button (enabled/disabled) or the progress of a task (started/completed).

  • Defining options: Enumerations can be used to define a set of options for a particular setting or configuration.

  • Improving code readability: Enumerations make code more readable and self-documenting by using named constants instead of raw values.

Complete Code Implementations

Example 1: Representing States

# Define an enum class for button states
class ButtonState(Enum):
    ENABLED = 1
    DISABLED = 2

# Create a button object and set its state
button = Button()
button.state = ButtonState.DISABLED

# Check the button state
if button.state == ButtonState.DISABLED:
    print("Button is disabled")

Example 2: Defining Options

# Define an enum class for configuration options
class ConfigOption(Enum):
    LOW = 1
    MEDIUM = 2
    HIGH = 3

# Get the user's choice for the configuration option
choice = int(input("Enter your choice (1-3): "))

# Convert the choice to the corresponding enum member
option = ConfigOption(choice)

# Print the selected option
print(f"Selected option: {option.name}")

**format Method**

The __format__ method in the enum module is used to specify how an Enum object is represented when used in string formatting operations, such as format() or f-strings.

Simplified Explanation:

Imagine you have a set of colors represented as an Enum called Color:

from enum import Enum

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

By default, when you use str(Color.RED) or f"{Color.RED}", you'll get 'Color.RED'. This is because __str__ returns the name of the enum member.

However, you can customize the string representation using __format__. For example, you can define __format__ to return only the name of the color:

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

    def __format__(self, spec):
        return self.name

Now, str(Color.RED) and f"{Color.RED}" will return 'RED'.

Real-World Applications:

  • Customizing logging output: You can use __format__ to control how enums are displayed in log messages.

  • Creating custom JSON serializers: By overriding __format__, you can define how enum values are converted to JSON.

  • Providing human-readable descriptions: You can use __format__ to return a description or additional information about the enum value.

Code Example:

Here's an example of a custom __format__ method that returns both the name and value of the enum:

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

    def __format__(self, spec):
        return f'{self.name}: {self.value}'

color = Color.RED
print(f"{color}")

Output:

RED: 1

Potential Applications:

  • Status codes: To provide descriptive messages for error codes.

  • Configuration settings: To make configuration files more human-readable.

  • Data analysis: To create custom visualizations that display enum values in a specific format.


What is IntEnum?

IntEnum is a special type of enumeration that allows you to use integer values instead of strings for the members. This can be useful if you need to perform mathematical operations on the members or if you want to use them as indices in an array.

Creating an IntEnum

To create an IntEnum, you use the IntEnum class:

from enum import IntEnum

class Number(IntEnum):
    ONE = 1
    TWO = 2
    THREE = 3

This creates an enumeration with three members: ONE, TWO, and THREE. Each member is assigned an integer value, starting from 1.

Using IntEnum

You can use IntEnum members just like regular integers:

print(Number.THREE)  # Output: 3
print(Number.ONE + Number.TWO)  # Output: 3
print(Number.THREE == 3)  # Output: True

You can also use IntEnum members as indices in arrays:

numbers = [10, 20, 30]
print(numbers[Number.TWO])  # Output: 20

Auto-Incrementing Values

By default, IntEnum members are assigned integer values starting from 1. However, you can use the auto() function to automatically increment the values of the members:

from enum import IntEnum, auto

class Number(IntEnum):
    ONE = auto()
    TWO = auto()
    THREE = auto()

This will create an enumeration with three members: ONE, TWO, and THREE. Each member will be assigned an integer value starting from 1, but the values will be automatically incremented by 1 for each member.

Real-World Applications

IntEnum can be used in a variety of real-world applications, including:

  • Representing error codes

  • Representing states in a finite state machine

  • Representing the different types of objects in a system

  • Representing the different permissions that a user can have

Potential Applications

Here are some potential applications for IntEnum in real-world code:

  • A game development library could use IntEnum to represent the different types of units in a game.

  • A web application could use IntEnum to represent the different states of a user account.

  • A database library could use IntEnum to represent the different types of database operations.


What is an Enum?

An enum is a way to represent a set of values that cannot be changed. For example, you could create an enum to represent the days of the week:

from enum import Enum

class DayOfWeek(Enum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 7

Once you have created an enum, you can use its members to represent the values in your code:

day_of_week = DayOfWeek.MONDAY

What is a StrEnum?

A StrEnum is a type of enum where the members are represented as strings instead of numbers. This can be useful in situations where you want to use the enum values in a context where strings are required, such as in a database or a JSON file.

from enum import StrEnum

class Gender(StrEnum):
    MALE = "male"
    FEMALE = "female"
    OTHER = "other"

Creating a StrEnum

To create a StrEnum, you simply need to use the StrEnum base class instead of the Enum base class:

from enum import StrEnum

class Gender(StrEnum):
    MALE = "male"
    FEMALE = "female"
    OTHER = "other"

Using a StrEnum

Once you have created a StrEnum, you can use its members just like you would use the members of a regular enum:

gender = Gender.MALE

You can also use the str() function to convert a StrEnum member to a string:

gender_str = str(gender)

Applications of StrEnums

StrEnums can be used in a variety of applications, including:

  • Databases: StrEnums can be used to represent the values in a database table.

  • JSON files: StrEnums can be used to represent the values in a JSON file.

  • User interfaces: StrEnums can be used to represent the options in a user interface.

Example

Here is a complete example showing how to use a StrEnum:

 from enum import StrEnum

 class Gender(StrEnum):
    MALE = "male"
    FEMALE = "female"
    OTHER = "other"


# Create a dictionary of genders
genders = {
    Gender.MALE: "Male",
    Gender.FEMALE: "Female",
    Gender.OTHER: "Other",
}


# Get the gender of a user
gender = Gender.MALE


# Print the gender of the user
print(genders[gender])

Enums and Flags: A Beginner's Guide

Enums (Enumerations)

Imagine you have a list of choices, like the days of the week. Instead of writing out "Monday", "Tuesday", etc., you can use numbers to represent each day, like this:

from enum import Enum

class Days(Enum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 7

Now, you can use the Days enum to refer to specific days by number. For example:

print(Days.MONDAY)  # Output: Days.MONDAY
print(Days.MONDAY.name)  # Output: 'MONDAY'
print(Days.MONDAY.value)  # Output: 1

Flags

Flags are similar to enums, but they have a special superpower: they can be combined using bitwise operators like &, |, ^, and ~. This is useful when you have a set of options that can be turned on or off independently.

For example, imagine you have a set of permissions for a user:

from enum import Flag

class Permissions(Flag):
    READ = 1
    WRITE = 2
    DELETE = 4

Now, you can use the Permissions flag to represent different combinations of permissions:

user_permissions = Permissions.READ | Permissions.WRITE  # User can read and write

if user_permissions & Permissions.DELETE:  # Check if user has delete permission
    print("User has delete permission")

Real World Applications

  • Enums can be used to represent any set of fixed choices, such as:

    • Days of the week

    • Months of the year

    • Sizes (small, medium, large)

    • Colors (red, green, blue)

  • Flags can be used to represent sets of options that can be combined, such as:

    • User permissions (read, write, delete)

    • File permissions (read, write, execute)

    • System settings (enabled, disabled)

Complete Code Examples

Enum

>>> from enum import Enum

>>> class Days(Enum):
...     MONDAY = 1
...     TUESDAY = 2
...     WEDNESDAY = 3
...     THURSDAY = 4
...     FRIDAY = 5
...     SATURDAY = 6
...     SUNDAY = 7

>>> Days.MONDAY
<Days.MONDAY: 1>
>>> Days.MONDAY.name
'MONDAY'
>>> Days.MONDAY.value
1

Flag

>>> from enum import Flag

>>> class Permissions(Flag):
...     READ = 1
...     WRITE = 2
...     DELETE = 4

>>> user_permissions = Permissions.READ | Permissions.WRITE
>>> user_permissions
<Permissions.READ: 3>
>>> user_permissions & Permissions.DELETE
<Permissions.DELETE: 4>
>>> if user_permissions & Permissions.DELETE:
...     print("User has delete permission")
...
User has delete permission

**contains Method in Enum**

The __contains__ method in Python's enum module checks if a specified value is part of the enum class.

Simplified Explanation:

Imagine you have a list of colors (an enum class):

from enum import Enum

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

Now, you can use the __contains__ method to check if a color is in the list:

>>> "RED" in Color
True
>>> "YELLOW" in Color
False

Real-World Applications:

  • Validating user input: Ensuring that users enter valid values from a predefined set.

  • Creating role-based access control: Limiting access to certain features based on the user's role (an enum value).

  • Representing finite states: Modeling the different states of an object or system using enum values.

Code Implementation:

from enum import Enum

class FileStatus(Enum):
    NEW = 1
    OPEN = 2
    SAVED = 3
    CLOSED = 4

# Check if the file is open
if FileStatus.OPEN in FileStatus:
    # Perform actions for an open file

# Check if a file status is not in the enum
if "PROCESSING" not in FileStatus:
    # Handle unsupported file status

Potential Applications:

  • Validating file status in a file management system.

  • Representing the states of a workflow in a project management tool.


Overview

Python's enum module provides a way to define enumerated types, which are sets of named values that represent different options or choices. Enumerated types are useful for representing choices that are limited to a specific set of values, such as the colors of a traffic light or the days of the week.

Creating an Enum

To create an enum, you use the Enum class and provide a list of named values:

from enum import Enum

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

This creates an enum called Color with three named values: RED, GREEN, and BLUE. Each named value is assigned an integer value, which is used to represent the value of the enum member. You can access the integer value of an enum member using the value attribute:

>>> Color.RED.value
1

Using an Enum

You can use an enum to represent a choice in your code by assigning it to a variable:

color = Color.RED

You can then use the name attribute of the enum member to get the name of the choice:

>>> color.name
'RED'

Iterating over an Enum

You can iterate over the members of an enum using the iter() method:

>>> for color in Color:
...     print(color)
...
<Color.RED: 1>
<Color.GREEN: 2>
<Color.BLUE: 3>

Real-World Applications

Enums are used in a variety of real-world applications, including:

  • Representing the states of a finite state machine

  • Representing the options in a user interface

  • Representing the values of a database column

  • Representing the permissions that a user has

Code Implementations and Examples

Here is a complete code implementation of an enum representing the days of the week:

from enum import Enum

class DayOfWeek(Enum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 7

# Get the name of the day of the week
day = DayOfWeek.MONDAY
day_name = day.name
print(day_name)  # Output: MONDAY

# Iterate over the days of the week
for day in DayOfWeek:
    print(day)

You can use this enum to represent the day of the week in your code, ensuring that you always use a valid day value.


**len Method in Python's Enum Module**

Simplified Explanation:

The __len__ method in the enum module lets you find out how many members (or options) there are in an enum class.

Detailed Explanation:

An enum class is a collection of related constants. Each constant is given a name and a value. The __len__ method returns the number of constants in the enum class.

Example:

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3
    WHITE = 10

num_colors = len(Color)

print(num_colors)  # Output: 4

In this example, the Color enum class has four constants: RED, GREEN, BLUE, and WHITE. So, the __len__ method returns 4.

Applications in Real World:

The __len__ method can be useful in various scenarios, such as:

  • Iterating over all the members of an enum class:

    for color in Color:
        print(color)
  • Checking if a particular member exists in an enum class:

    if Color.GREEN in Color:
        print("GREEN is a valid color")
  • Displaying the number of options available in an enum:

    print("There are", len(Color), "colors available")

Python's enum Module

What is an enum?

An enum, or enumerated type, is a way to define a set of named constants. In other words, it's a way to give meaningful names to specific values.

Using the __bool__ Method

The __bool__ method is called when you use the bool() function on an enum member. It returns True if any members in the enum are set, or False if all members are unset.

Example:

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 4

color = Color.GREEN

if color:
    print("The color is not black")
else:
    print("The color is black")

Output:

The color is not black

In this example, the Color.GREEN enum member is set, so the __bool__ method returns True and the if statement is executed.

Real-World Applications

Enums are useful in any situation where you need to represent a set of fixed values. For example, they can be used to represent:

  • The days of the week

  • The months of the year

  • The colors of the rainbow

  • The states of a traffic light

  • The different modes of a computer

Code Implementations

Here are some complete code implementations of the enum module:

Example 1: Defining an enum

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 4

Example 2: Using an enum

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 4

color = Color.GREEN

if color == Color.GREEN:
    print("The color is green")

Example 3: Using the __bool__ method

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 4

color = Color.GREEN

if color:
    print("The color is not black")
else:
    print("The color is black")

Method: __or__

Simplified Explanation:

This method combines the current flag (the enum value you're calling this method on) with another flag. It uses a bitwise OR operation, which sets each bit to 1 if that bit is 1 in either of the flags.

Example:

Let's say you have an enum called Color with values for RED and GREEN.

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2

When you call Color.RED | Color.GREEN, the result will be a new flag that has the bits for both RED and GREEN set to 1. In binary, this would be:

RED:    0001
GREEN:  0010
OR:     0011

Which represents the value 3.

Real-World Example:

You could use this method to combine multiple flags that represent different options or configurations. For example, in a game, you could have a flag for "show health bar" and another flag for "show damage numbers". You could then combine these flags using __or__ to display both health bars and damage numbers.

Improved Example:

Here's an improved example that shows how you can use __or__ to combine multiple flags:

import enum

class Options:
    SHOW_HEALTH_BAR = 1
    SHOW_DAMAGE_NUMBERS = 2

def configure_display(options):
    if options & Options.SHOW_HEALTH_BAR:
        print("Show health bar")
    if options & Options.SHOW_DAMAGE_NUMBERS:
        print("Show damage numbers")

options = Options.SHOW_HEALTH_BAR | Options.SHOW_DAMAGE_NUMBERS
configure_display(options)

Output:

Show health bar
Show damage numbers

**Method: **and****

This method performs a binary AND operation between the current Color object and another Color object or integer.

In Python, the bitwise AND operator (&) checks if corresponding bits in two numbers are both 1. If both bits are 1, the result is 1; otherwise, the result is 0.

Syntax:

__and__(self, other)

Parameters:

  • self: The current Color object.

  • other: Another Color object or integer.

Return Value:

A new Color object with the flags resulting from the binary AND operation.

Example:

from enum import Enum

class Color(Enum):
    RED = 1
    BLUE = 2
    GREEN = 4
    PURPLE = RED | BLUE  # 3

purple = Color.PURPLE
white = Color.WHITE  # 0

print(purple & white)  # Output: <Color.RED|BLUE: 5>
print(purple & Color.GREEN)  # Output: <Color: 0>

In the first example, purple & white results in a new Color object with the value 5, which is the red and blue bits set. This is because the red and blue bits in both purple and white are 1.

In the second example, purple & Color.GREEN results in a new Color object with the value 0. This is because the green bit in purple is 0, and any bitwise operation with 0 will result in 0.

Real-World Applications:

Binary AND operations are useful in many real-world applications, such as:

  • Checking if a flag is set in a configuration file.

  • Determining if a user has a specific role or permission.

  • Combining different colors to create new color mixtures.


Method: xor(self, other)

Simplified Explanation:

This method combines two colors (represented as flags) by performing a binary exclusive OR (XOR) operation on their flags.

Detailed Explanation:

In Python's enum module, each enum member has a unique flag that is represented as an integer. The __xor__ method takes two enum members and returns a new enum member with a flag that is the result of an XOR operation between the flags of the two input members.

Code Snippet:

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 4

purple = Color.RED | Color.BLUE  # 3
white = Color.GREEN | Color.BLUE  # 6

# XOR purple and white
green = purple ^ white  # 2

# XOR purple and Color.GREEN
red_green_blue = purple ^ Color.GREEN  # 7

Real-World Complete Code Implementation:

A simple program that displays the color resulting from XORing two colors:

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 4

def main():
    purple = Color.RED | Color.BLUE  # 3
    white = Color.GREEN | Color.BLUE  # 6

    # XOR purple and white
    green = purple ^ white  # 2

    # Display the resulting color
    print(green)

if __name__ == "__main__":
    main()

Output:

<Color.GREEN: 2>

Potential Applications in the Real World:

This method can be used in applications that deal with bitwise operations, such as:

  • Image processing: Combining or subtracting colors to create different effects.

  • Data manipulation: Filtering or selecting data based on specific bit patterns.

  • Cryptography: Encrypting or decrypting data using bitwise operations.


  • Method: invert

    • Purpose: Inverts the flags in an enum member.

    • Simplified Explanation: It returns a new enum member that contains all the flags in the original enum member's type that are not present in the original member.

    • Code Snippet:

      from enum import Enum
      
      class Color(Enum):
          RED = 1
          GREEN = 2
          BLUE = 4
          PURPLE = RED | BLUE
      
      white = Color(0)  # No flags set
      inverted_white = ~white
      print(inverted_white)  # <Color: 7> (All flags set)
      
      purple = Color.PURPLE
      inverted_purple = ~purple
      print(inverted_purple)  # <Color.GREEN: 2> (Only GREEN flag set)
      
      red = Color.RED
      inverted_red = ~red
      print(inverted_red)  # <Color.GREEN|BLUE: 6> (Both GREEN and BLUE flags set)
  • Real-World Application:

    • Checking for the absence of specific flags in a set of flags.

    • Inverting flags to represent opposite or complementary states.


Customizing the Representation of Unnamed Numeric Members

In Python's enum module, unnamed numeric members (those without specified names) can be customized using the _numeric_repr_ function.

_numeric_repr_ Function:

The _numeric_repr_ function specifies how unnamed numeric members should be represented as strings.

Default Behavior:

By default, the repr function is used to convert unnamed numeric members to strings.

Customizing the Representation:

To customize the representation, provide a function to the _numeric_repr_ attribute of the Enum class. This function should take a single argument, the unnamed numeric member, and return a string representing it.

Common Customization Options:

  • hex: Converts the member to a hexadecimal string.

  • oct: Converts the member to an octal string.

  • Other custom functions can be defined to provide specific formats.

Example:

Consider the following Color enum:

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3
    _numeric_repr_ = lambda i: f"Color: {i}"

Here, the _numeric_repr_ function formats unnamed numeric members as "Color: <number>".

Output:

Color(0)  # doctest: +SKIP
<Color: 0>

Applications in the Real World:

Customizing _numeric_repr_ can be useful in scenarios where:

  • You want to provide a more informative string representation of unnamed numeric members.

  • You need to integrate with external systems that require a specific numeric format.

  • You want to create enums with numeric members that have specific semantic meanings.


IntFlag

IntFlag is a special type of enum that can represent multiple values at once as integers. It's like a set of flags that can be combined and compared.

IntFlag in Action

Let's create an IntFlag called Color:

from enum import IntFlag

class Color(IntFlag):
    RED = 1
    GREEN = 2
    BLUE = 4

Now, we can set multiple colors by combining their integer values:

my_color = Color.RED | Color.GREEN  # Result: 3 (1 + 2)

IntFlag Operations

IntFlags support basic integer operations like addition and subtraction:

new_color = my_color + Color.BLUE  # Result: 7 (3 + 4)

Comparing IntFlags

You can also compare IntFlags like sets:

if Color.RED in my_color:
    print("Red is in the mix!")

Example: Controlling LED Lights

IntFlags can be useful for controlling multiple LED lights. Each light can be assigned a unique IntFlag value, allowing you to control them all simultaneously.

import RPi.GPIO as GPIO

class Light(IntFlag):
    RED = 1
    GREEN = 2
    BLUE = 4

GPIO.output(11, Light.RED) # Turn on the red LED

Benefits of IntFlags

  • Efficiency: IntFlags can represent multiple values compactly using integers.

  • Clarity: They make it clear which values are being combined.

  • Extensibility: You can easily add new flags without breaking existing code.

Other Flag Operations

IntFlags also support other operations, including:

  • Intersection (&): Returns a new IntFlag with only the values that appear in both flags.

  • Union (|): Returns a new IntFlag with all the values that appear in either flag.

  • Exclusive OR (^): Returns a new IntFlag with the values that appear in one flag but not the other.

  • Complement (~): Returns a new IntFlag with all the values not present in the original flag.

  • Zero-valued Flag (Color(0)): Represents the absence of all flags.


ReprEnum

Simplified Explanation:

  • ReprEnum is a special type of Enum that uses a different way to represent its values as strings.

  • By default, Enum values are represented as their names (e.g., Enum.Name).

  • ReprEnum uses the internal representation of the value instead (e.g., int for numbers, str for strings).

Code Snippet:

from enum import Enum, ReprEnum

class MyEnum(ReprEnum):
    One = 1
    Two = "two"

print(MyEnum.One)  # Output: 1
print(str(MyEnum.Two))  # Output: "two"

Real-World Applications:

  • If you want to store and retrieve values from a database or other system that expects specific representations for different types.

  • If you have custom string representations for your Enum values and want to use them instead of the default names.

Potential Applications:

  • Storing user preferences (e.g., "dark" or "light" theme).

  • Representing error codes or status messages (e.g., "success" or "failure").

  • Creating language-independent representations of values (e.g., representing numbers with their digits instead of their English names).


EnumCheck

An EnumCheck is a set of rules that are used to verify that an enum value is valid. These rules can be used to ensure that the enum value is within a certain range, or that it has a specific value.

Usage

To use an EnumCheck, you can pass it as an argument to the verify decorator. The verify decorator will then check the enum value against the rules in the EnumCheck and raise a ValueError if any of the rules are violated.

For example, the following code defines an enum with a EnumCheck that ensures that the enum value is within the range of 1 to 10:

from enum import Enum, EnumCheck

class MyEnum(Enum):
    ONE = 1
    TWO = 2
    THREE = 3

    # Define the EnumCheck
    enum_check = EnumCheck(min=1, max=10)

    # Use the EnumCheck with the verify decorator
    @verify(enum_check)
    def my_method(self):
        pass

If you try to call the my_method method with an enum value that is not within the range of 1 to 10, a ValueError will be raised.

Applications

EnumChecks can be used in a variety of applications, such as:

  • Validating input data

  • Ensuring that enum values are consistent with other data

  • Preventing invalid enum values from being used in calculations

Real-World Example

The following code shows a real-world example of how an EnumCheck can be used to validate input data:

from enum import Enum, EnumCheck

# Define an enum for the different types of animals
class AnimalType(Enum):
    DOG = 1
    CAT = 2
    FISH = 3

    # Define an EnumCheck to ensure that the animal type is valid
    enum_check = EnumCheck(AnimalType, message="Invalid animal type")

# Get the animal type from the user
animal_type = input("Enter the animal type (dog, cat, or fish): ")

# Verify the animal type using the EnumCheck
try:
    animal_type = AnimalType[animal_type.upper()]
    animal_type.verify(enum_check)
except ValueError as e:
    print(e.args[0])
    exit()

# Do something with the animal type
if animal_type == AnimalType.DOG:
    print("You have a dog.")
elif animal_type == AnimalType.CAT:
    print("You have a cat.")
elif animal_type == AnimalType.FISH:
    print("You have a fish.")

This code uses an EnumCheck to ensure that the animal type entered by the user is valid. If the user enters an invalid animal type, a ValueError will be raised and the program will exit.


Attribute: UNIQUE

Explanation:

The UNIQUE attribute in the enum module ensures that each value in an enumeration has only one name. This means that you cannot have multiple names for the same value.

Simplified Example:

Imagine you have an enumeration for colors:

from enum import Enum, verify, UNIQUE

@verify(UNIQUE)
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

Usage:

You can use the UNIQUE attribute to prevent duplicate names for values. For example, if you try to create a value with a duplicate name, you will get an error:

try:
    Color.CRIMSON = 1
except ValueError as e:
    print(e)

Output:

aliases found in <enum 'Color'>: CRIMSON -> RED

Potential Applications:

The UNIQUE attribute is useful when you want to ensure that each value in an enumeration is unique. This can be important in situations where the values are used as keys or identifiers.


Enum.CONTINUOUS

Purpose:

This attribute ensures that there are no gaps in the values assigned to enum members.

How it Works:

When assigning values to enum members, they should be consecutive integers. For example:

from enum import Enum

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

In this example, the enum members RED, GREEN, and BLUE are assigned consecutive values.

If you attempt to define an enum member with a non-consecutive value, Enum.CONTINUOUS will raise a ValueError. For instance:

from enum import Enum, verify, CONTINUOUS

@verify(CONTINUOUS)
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 5  # This will cause an error

Traceback (most recent call last):
...
ValueError: invalid enum 'Color': missing values 3, 4

Real-World Applications:

Enum.CONTINUOUS is useful in situations where the values assigned to enum members need to be consecutive. For example, if you create an enum for weekdays, it makes sense to have them assigned in the order they appear in the week:

from enum import Enum

class Weekday(Enum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 7

Using Enum.CONTINUOUS ensures that you don't accidentally skip a weekday or assign duplicate values.


Named Flags

Explanation:

Named flags ensure that when you combine flags, you only use those that have specific names. This helps avoid creating unexpected combined values.

Simplified Example:

Imagine you have a flag called "Color" with values "RED", "GREEN", and "BLUE". If you wanted to create a new color by combining "RED" and "GREEN", you would expect "YELLOW". However, if you allowed unnamed flags, someone could create a flag called "YELLOW" without you knowing. Named flags prevent this by ensuring that only the flags you name can be combined.

Code Snippet:

from enum import Flag, verify, NAMED_FLAGS

@verify(NAMED_FLAGS)
class Color(Flag):
    RED = 1
    GREEN = 2
    BLUE = 4

In this example, the NAMED_FLAGS decorator ensures that only named flags (RED, GREEN, BLUE) can be used.

Real-World Applications:

  • Ensuring consistency and avoiding ambiguity when combining flags.

  • Preventing unexpected combinations of flags that could lead to errors or undefined behavior.

Note:

Named flags work best with integer-valued flags.


What is FlagBoundary?

FlagBoundary is a class that controls how out-of-range values are handled in the Flag class and its subclasses.

How it Works

When you create a Flag object, you can specify a FlagBoundary to control what happens when you try to set a value that is not in the range of valid values for that flag. There are two options for FlagBoundary:

  • CLIP: This option will clamp the value to the nearest valid value in the range. For example, if you have a flag with a range of 0 to 100, and you try to set it to 120, it will be clamped to 100.

  • ERROR: This option will raise a ValueError exception if you try to set a value that is out of range.

Real-World Example

Here is an example of how you can use FlagBoundary in a real-world application:

from enum import Flag, FlagBoundary

class MyFlag(Flag):
    OPTION1 = 1 << 0
    OPTION2 = 1 << 1
    OPTION3 = 1 << 2

    # This will clamp out-of-range values to the nearest valid value
    boundary = FlagBoundary.CLIP

In this example, we have defined a MyFlag class that has three options: OPTION1, OPTION2, and OPTION3. We have also specified a FlagBoundary of CLIP, which means that out-of-range values will be clamped to the nearest valid value.

Here is an example of how you can use the MyFlag class:

flag = MyFlag.OPTION1

# Try to set an out-of-range value
flag |= 1 << 10

# The value will be clamped to OPTION3
print(flag)  # prints MyFlag.OPTION3

In this example, we first create a MyFlag object with the value OPTION1. We then try to set an out-of-range value by bitwise ORing the flag with 1 << 10. However, since we have specified a FlagBoundary of CLIP, the value will be clamped to OPTION3.

Potential Applications

FlagBoundary can be used in a variety of real-world applications, such as:

  • Ensuring that data is within a valid range: You can use FlagBoundary to ensure that data is within a specific range of values. For example, you could use FlagBoundary to ensure that a user's age is between 0 and 120.

  • Preventing invalid state: You can use FlagBoundary to prevent invalid state


Enum.STRICT Attribute

Explanation

The STRICT attribute is an optional setting for Flag in Python's enum module. It controls how the Flag class behaves when given out-of-range values.

Default Behavior

By default, Flag objects with STRICT set to False allow out-of-range values. These values get stored as a combination of the valid flags.

STRICT Behavior

When STRICT is set to True, out-of-range values are not allowed. Attempting to create a Flag with an invalid value will raise a ValueError.

Code Snippet

from enum import Flag, STRICT, auto

class StrictFlag(Flag, boundary=STRICT):
    RED = auto()
    GREEN = auto()
    BLUE = auto()

# Out-of-range values cause a ValueError
try:
    strict_flag = StrictFlag(2**2 + 2**4)
except ValueError as e:
    print(e)

Output

<flag 'StrictFlag'> invalid value 20
    given 0b0 10100
  allowed 0b0 00111

Real-World Applications

The STRICT attribute ensures that only valid flags are used in a Flag object. This can be useful in applications where it's crucial to prevent invalid or unexpected values.

For example, consider a system that manages user permissions using a Flag enum:

from enum import Flag, STRICT, auto

class Permission(Flag, boundary=STRICT):
    READ = auto()
    WRITE = auto()
    DELETE = auto()

With STRICT set to True, invalid permissions will be rejected, preventing unauthorized access.


Attribute: CONFORM

When you create an enumeration with the CONFORM boundary, it means that when you try to assign a value that is out of range, instead of raising an error, the invalid values are removed, and a valid Flag value is returned.

For example, let's say you have the following enumeration:

from enum import Flag, CONFORM, auto

class ConformFlag(Flag, boundary=CONFORM):
    RED = auto()
    GREEN = auto()
    BLUE = auto()

Now, if you try to assign a value that is out of range, the invalid values are removed:

>>> ConformFlag(2**2 + 2**4)
<ConformFlag.BLUE: 4>

In this case, the 2**2 (4) and 2**4 (16) are both invalid values for the ConformFlag enumeration, so they are removed, and the BLUE flag is returned, which has a value of 4.

Real-world applications

The CONFORM boundary is useful in situations where you want to handle out-of-range values gracefully. For example, you could use it to handle invalid input from a user or to ensure that values stored in a database are always valid.

Here is a real-world example of how you could use the CONFORM boundary:

from enum import Flag, CONFORM, auto

class Color(Flag, boundary=CONFORM):
    RED = auto()
    GREEN = auto()
    BLUE = auto()

def get_color(color_string):
    """Returns a Color enum value for the given color string."""
    try:
        return Color[color_string.upper()]
    except KeyError:
        return Color.BLACK  # Default to black if the color string is invalid

color = get_color("purple")
print(color)  # Output: <Color.BLACK: 0>

In this example, the get_color() function uses the CONFORM boundary to handle invalid color strings gracefully. If the color string is invalid, the function returns the Color.BLACK flag value instead of raising an error.


Simplified Explanation of the EJECT Attribute in Python's enum Module

EJECT Attribute:

When using flags with the EJECT boundary, any value that is assigned to the flag but falls outside its predefined range is automatically removed from the flag set.

Example:

from enum import Flag, EJECT, auto

# Define a flag enum with the EJECT boundary
class EjectFlag(Flag, boundary=EJECT):
    RED = auto()
    GREEN = auto()
    BLUE = auto()

# Assign a value outside the set of flags
result = EjectFlag(2**2 + 2**4)  # This is equivalent to 20

# Check the result
print(result)  # Output: 20

Explanation:

In the example above, we create a flag enum called EjectFlag with the EJECT boundary. The EJECT boundary tells the enum that any value assigned to the flag that is outside the range of defined flags should be removed from the flag set.

When we assign the value 20 to the EjectFlag, it is automatically removed from the flag set since it is not one of the defined flags (RED, GREEN, or BLUE). Therefore, when we print the value of result, we get 20 as an integer, not as a flag.

Real-World Applications:

The EJECT boundary is useful when you want to ensure that only specific values are represented by the flags. For example, you could use it to represent the days of the week:

from enum import Flag, EJECT, auto

class Day(Flag, boundary=EJECT):
    MONDAY = auto()
    TUESDAY = auto()
    WEDNESDAY = auto()
    THURSDAY = auto()
    FRIDAY = auto()
    SATURDAY = auto()
    SUNDAY = auto()

# Assign an invalid day
result = Day(8)

# Check the result
print(result)  # Output: 0

In this example, the Day enum has the EJECT boundary, which means any value assigned to the flag that is not one of the defined days (e.g., 8) is automatically removed from the flag set. When we print the value of result, we get 0 as an integer, not as a flag.


Attributes

  • KEEP: Out-of-range values are kept, and their Flag membership is preserved. This is the default for IntFlag.

Supported __dunder__ Names

  • ~EnumType.__members__: A read-only ordered mapping of member_name: member pairs. It's only available on the class.

Supported _sunder_ Names

  • ~EnumType._add_alias_: Adds a new name as an alias to an existing member.

  • ~EnumType._add_value_alias_: Adds a new value as an alias to an existing member.

  • ~Enum._name_: The name of the member.

  • ~Enum._value_: The value of the member. Can be set in __new__.

  • ~Enum._missing_: A lookup function used when a value is not found. Can be overridden.

  • ~Enum._ignore_: A list of names that will not be transformed into members and will be removed from the final class.

  • ~Enum._order_: No longer used, kept for backward compatibility.

  • ~Enum._generate_next_value_: Used to get an appropriate value for an enum member. Can be overridden.

Real-World Examples

Using KEEP:

from enum import Flag, KEEP, auto

class Colors(Flag, boundary=KEEP):
    RED = auto()
    GREEN = auto()
    BLUE = auto()

print(Colors(2**2 + 2**4))  # Outputs <Colors.BLUE|16: 20>

Using __members__:

from enum import Enum

class Sizes(Enum):
    SMALL = 1
    MEDIUM = 2
    LARGE = 3

print(Sizes.__members__)  # Outputs {'SMALL': <Sizes.SMALL: 1>, 'MEDIUM': <Sizes.MEDIUM: 2>, 'LARGE': <Sizes.LARGE: 3>}

Using _add_alias_:

from enum import Enum

class Colors(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

Colors._add_alias('primary', Colors.RED)
print(Colors.primary)  # Outputs <Colors.RED: 1>

Applications:

  • KEEP: Used when you want to allow out-of-range values for a Flag enum.

  • __members__: Provides a complete list of members in the enum class.

  • _add_alias_ and _add_value_alias_: Useful for adding aliases to enum members.

  • _missing_ and _generate_next_value_: Advanced customization options for enum behavior.


auto

auto can be used in place of a value in an Enum. If used, the Enum machinery will call an Enum's _generate_next_value_ to get an appropriate value.

For Enum and IntEnum, that appropriate value will be the last value plus one; for Flag and IntFlag, it will be the first power-of-two greater than the highest value; for StrEnum, it will be the lower-case of the member's name. Care must be taken if mixing auto() with manually specified values.

auto instances are only resolved when at the top level of an assignment:

  • FIRST = auto() will work (auto() is replaced with 1);

  • SECOND = auto(), -2 will work (auto is replaced with 2, so 2, -2 is used to create the SECOND enum member;

  • THREE = [auto(), -3] will not work (<auto instance>, -3 is used to create the THREE enum member)

In priority, auto takes precedence over explicit values. Thus, both of the following will raise ValueError:

  • FIRST = auto(), 1

  • FIRST = 1, auto()

generate_next_value

_generate_next_value_ can be overridden to customize the values used by auto.

Real-World Example

One potential application of auto is to generate unique IDs for objects. For example:

from enum import Enum

class MyEnum(Enum):
    FIRST = auto()
    SECOND = auto()
    THIRD = auto()

print(MyEnum.FIRST.value)  # 1
print(MyEnum.SECOND.value)  # 2
print(MyEnum.THIRD.value)  # 3

In this example, auto() is used to generate the values for the MyEnum members. The values are assigned in the order that the members are defined, starting from 1.

Another potential application of auto is to generate unique names for objects. For example:

from enum import StrEnum

class MyStrEnum(StrEnum):
    FIRST = auto()
    SECOND = auto()
    THIRD = auto()

print(MyStrEnum.FIRST.value)  # 'first'
print(MyStrEnum.SECOND.value)  # 'second'
print(MyStrEnum.THIRD.value)  # 'third'

In this example, auto() is used to generate the names for the MyStrEnum members. The names are assigned in the order that the members are defined, starting from the lowercase version of the member name.


What is a decorator?

A decorator is a function that takes another function as an argument and returns a modified version of that function.

What is the property decorator?

The @property decorator is used to create a read-only property. This means that the property can be accessed like a normal attribute, but it cannot be assigned to.

How is the property decorator used with enumerations?

The @property decorator can be used with enumerations to create member attributes that have the same names as members themselves. This can be useful for making the enumeration more readable and easier to use.

Example:

from enum import Enum

class MyEnum(Enum):
    A = 1
    B = 2
    C = 3

    @property
    def value(self):
        return self.value

    @property
    def name(self):
        return self.name

In this example, the @property decorator is used to create the value and name attributes. These attributes can be accessed like normal attributes, but they cannot be assigned to.

Real-world applications:

The @property decorator can be used in a variety of real-world applications, such as:

  • Creating read-only properties for data that should not be changed.

  • Creating properties that are calculated from other data.

  • Creating properties that provide a different interface to the underlying data.

Potential benefits:

The @property decorator can provide a number of benefits, such as:

  • Improved readability: The @property decorator can make your code more readable by making it clear which attributes are read-only.

  • Easier to use: The @property decorator can make your code easier to use by providing a consistent interface for accessing data.

  • More flexible: The @property decorator can be used to create properties that are calculated from other data or that provide a different interface to the underlying data.


What is a decorator?

A decorator is a function that takes another function as an argument and returns a new function. Decorators are used to modify the behavior of the decorated function without modifying the function itself.

What is the @unique decorator?

The @unique decorator is a decorator that is specifically designed for enums. An enum is a data type that represents a set of named constants. For example, the following code defines an enum that represents the four cardinal directions:

from enum import Enum

class Direction(Enum):
    NORTH = 1
    EAST = 2
    SOUTH = 3
    WEST = 4

The @unique decorator can be used to ensure that all of the values in an enum are unique. For example, the following code will raise an error because the value of FOUR is the same as the value of THREE:

from enum import Enum, unique

@unique
class Direction(Enum):
    NORTH = 1
    EAST = 2
    SOUTH = 3
    WEST = 4
    FOUR = 3

How to use the @unique decorator?

To use the @unique decorator, simply place it before the definition of the enum. For example:

from enum import Enum, unique

@unique
class Direction(Enum):
    NORTH = 1
    EAST = 2
    SOUTH = 3
    WEST = 4

Real-world applications of the @unique decorator

The @unique decorator can be used in any situation where you need to ensure that a set of values is unique. For example, the @unique decorator can be used to ensure that:

  • The keys in a dictionary are unique

  • The values in a list are unique

  • The members of an enum are unique

Potential applications of the @unique decorator in real world:

  • ensuring that there are no duplicate values in a data set

  • generating unique identifiers

  • creating unique keys for a database

  • creating unique names for files or directories


Topic 1: Python's Enum Module

Simplified explanation:

The enum module in Python allows you to create a list of fixed values, similar to an array. Each value has a unique name and an optional value.

Example:

from enum import Enum

# Create an enumeration for days of the week
class Days(Enum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 7

# Print the name of the first day of the week
print(Days.MONDAY.name)  # Output: MONDAY

# Print the value of the first day of the week
print(Days.MONDAY.value)  # Output: 1

Real-world application:

Enums are useful for representing choices that have a limited range of values, such as the days of the week, colors, or sizes.

Topic 2: Decorators

Simplified explanation:

Decorators are functions that can be applied to other functions to add extra functionality or modify their behavior.

Example:

def my_decorator(func):
    def wrapper(*args, **kwargs):
        print("Before calling the function")
        result = func(*args, **kwargs)
        print("After calling the function")
        return result
    return wrapper

# Apply the decorator to a function
@my_decorator
def my_function(x):
    print("Inside my_function")
    return x

# Call the decorated function
my_function(10)

Output:

Before calling the function
Inside my_function
After calling the function
10

Real-world application:

Decorators are commonly used to add logging, caching, or error handling to functions without modifying the original code.

Topic 3: verify Decorator

Simplified explanation:

The verify decorator in the enum module is specifically designed for enumerations. It allows you to specify constraints that should be checked on the values of the enumeration.

Example:

from enum import Enum, EnumCheck

# Create an enumeration with a constraint that all values must be positive
class PositiveNumbers(Enum):
    ONE = 1
    TWO = 2
    THREE = 3

    @EnumCheck
    def verify(self):
        if self.value <= 0:
            raise ValueError("Values must be positive")

# Create an instance of the enumeration
try:
    PositiveNumbers(-1)
except ValueError as e:
    print(str(e))  # Output: Values must be positive

Real-world application:

The verify decorator can be used to enforce business rules or data integrity constraints on enumerations. For example, you could use it to ensure that a status code is always a valid integer within a specific range.


Decorator

A decorator is a function that takes another function as an argument and returns a new function. This technique allows the new function to have added functionality without modifying the original function.

Enum

An enum is a special type in Python that allows you to define a set of named constants. For example, you could define an enum representing the days of the week:

from enum import Enum

class Day(Enum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 7

member Decorator

The @member decorator is used to mark a function as a member of an enum. This means that the function will be available as an attribute of the enum. The member decorator can be used to define various types of members, such as methods, properties, and constants. For example, you could define a function that returns the name of a day of the week:

@member
def name(self):
    return self.name

This function can be used as an attribute of the Day enum:

>>> Day.MONDAY.name
'MONDAY'

Real-World Applications

Enums can be used in a variety of real-world applications, such as:

  • Representing the states of a system

  • Representing the types of objects in a system

  • Representing the permissions that a user has

  • Representing the error codes that a function can return

Example

The following code shows a complete implementation of an enum that represents the days of the week:

from enum import Enum

class Day(Enum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 7

    @member
    def name(self):
        return self.name

    @member
    def is_weekday(self):
        return self in [Day.MONDAY, Day.TUESDAY, Day.WEDNESDAY, Day.THURSDAY, Day.FRIDAY]

This enum can be used to represent the days of the week in a variety of applications. For example, it could be used to control the behavior of a program that runs on a weekly basis.


Decorator

A decorator is a function that modifies the behavior of another function. In Python, decorators are defined using the @ symbol, like this:

def my_decorator(func):
    def wrapper(*args, **kwargs):
        # Do something before calling `func`
        result = func(*args, **kwargs)
        # Do something after calling `func`
        return result
    return wrapper

Use of @nonmember decorator in enums

The @nonmember decorator is used in Python enums to indicate that the decorated target should not become a member of the enum. This is useful for targets that are helper functions or constants that are related to the enum, but should not be included in the enum's namespace.

Example of using @nonmember decorator in enums

from enum import Enum

class MyEnum(Enum):
    ONE = 1
    TWO = 2

    @nonmember
    def helper_function():
        pass

    @nonmember
    MY_CONSTANT = 42

In this example, the helper_function() and MY_CONSTANT are not members of the MyEnum enum. This means that they will not be accessible through the enum's namespace, like this:

MyEnum.helper_function()  # AttributeError: 'MyEnum' object has no attribute 'helper_function'
MyEnum.MY_CONSTANT  # AttributeError: 'MyEnum' object has no attribute 'MY_CONSTANT'

However, they can still be accessed directly from the class, like this:

MyEnum.helper_function
MyEnum.MY_CONSTANT

Potential applications of nonmember decorator in real world

The nonmember decorator can be used in enums to:

  • Define helper functions that are related to the enum, but should not be included in the enum's namespace.

  • Define constants that are related to the enum, but should not be included in the enum's namespace.


Simplified Explanation of global_enum Decorator

What is it?

The global_enum decorator is a special tool in Python that helps make it easier to work with enums (short for "enumerations").

What are enums?

Enums are like special lists that contain a set of related values, each with a unique name. For example, you could have an enum called Fruit that contains the values APPLE, ORANGE, and BANANA.

What does the global_enum decorator do?

Normally, when you create an enum, the values are associated with the enum class itself. This means that if you want to use an enum value outside of the class, you have to specify the class name first.

For example:

from enum import Enum

class Fruit(Enum):
    APPLE = 1
    ORANGE = 2
    BANANA = 3

# Print the name of the first fruit
print(Fruit.APPLE.name)  # Output: 'APPLE'

The global_enum decorator changes this behavior. When you apply it to an enum, it makes the enum values global, meaning you can use them without specifying the class name.

@global_enum
class Fruit(Enum):
    APPLE = 1
    ORANGE = 2
    BANANA = 3

# Print the name of the first fruit
print(APPLE.name)  # Output: 'APPLE'

Real-World Application

The global_enum decorator is useful when you want to export the enum values to the global namespace. This can make it easier to use the enum values in other parts of your code or when working with third-party libraries.

For example, the Python standard library includes a global enum called re.RegexFlag that contains flags for regular expressions. This allows you to use the flags in regular expression patterns without having to specify the enum class name:

import re

# Compile a regular expression with the IGNORECASE flag
pattern = re.compile(r'pattern', flags=re.IGNORECASE)

Complete Code Implementation

Here is a complete code implementation of an enum decorated with global_enum:

from enum import global_enum

@global_enum
class Fruit(Enum):
    APPLE = 1
    ORANGE = 2
    BANANA = 3

# Print the name of the first fruit
print(APPLE.name)  # Output: 'APPLE'

Understanding Enum Flag Values

Flag Values

In Python, flag values are represented by integers or strings that represent multiple options or settings. They are commonly used to control behavior or settings for a program or function.

show_flag_values() Function

The show_flag_values() function is used to retrieve a list of all the power-of-two integers contained in a flag value. This function is particularly useful for identifying which options or settings are activated within a flag.

Example:

from enum import Flag, IntFlag

# Create an IntFlag representing options
class Options(IntFlag):
    OPTION_A = 1
    OPTION_B = 2
    OPTION_C = 4

# Assign options
options = Options.OPTION_A | Options.OPTION_B

# Retrieve flag values
flag_values = show_flag_values(options)

# Print flag values
print(flag_values)  # Output: [1, 2]

In this example, the show_flag_values() function returns a list containing the values 1 and 2, representing the activated options, OPTION_A and OPTION_B.

Return Value

The show_flag_values() function returns a list containing the power-of-two integers that are present in the flag value.

Limitations of Enum Types

The IntEnum, StrEnum, and IntFlag types inherit certain limitations from their base types:

  • String representation: These types use the value instead of the name of the enum member when converting to a string.

  • Format string: The __format__ method also uses the value instead of the name.

Custom Enum Types

If you require different behavior for your enum types, you can create custom base classes or override methods in existing enum classes.

Example:

# Create a custom IntEnum that uses the name for string representation
class MyIntEnum(int, Enum):
    OPTION_A = 1
    OPTION_B = 2
    OPTION_C = 4

    def __str__(self):
        return self.name

# Create an enum using the custom base class
class MyOptions(MyIntEnum):
    OPTION_D = 8

# Retrieve a string representation of a value
print(str(MyOptions.OPTION_A))  # Output: 'OPTION_A'

Real-World Applications

Flag values are commonly used in a variety of applications, including:

  • Configuration management: Managing and setting options for applications or systems.

  • Permission control: Granting or denying access to specific features or resources.

  • Feature flags: Enabling or disabling experimental or unreleased features.

  • Bitwise operations: Combining multiple options or settings into a single value for efficient processing.