Python enum auto (original) (raw)

Skip to content

Summary: in this tutorial, you’ll learn about the enum auto() function to generate unique values for enumeration members.

Introduction to the enum auto() function #

The following example defines an enumeration with three members whose values are 1, 2, and 3:

`from enum import Enum

class State(Enum): PENDING = 1 FULFILLED = 2 REJECTED = 3`Code language: Python (python)

In this example, we manually assign integer values to the members of the enumeration.

To make it more convenient, Python 3.6 introduced the auto() helper class in the enum module, which automatically generates unique values for the enumeration members. For example:

`from enum import Enum, auto

class State(Enum): PENDING = auto() FULFILLED = auto() REJECTED = auto()

def __str__(self):
    return f'{self.name(self.value)}'`Code language: Python (python)

How it works.

By default, the auto() class generates a sequence of integer numbers starting from 1.

The following shows the values of the State enumeration’s members:

for state in State: print(state.name, state.value)Code language: Python (python)

Output:

PENDING 1 FULFILLED 2 REJECTED 3Code language: Python (python)

Here’s the complete script:

`from enum import Enum, auto

class State(Enum): PENDING = auto() FULFILLED = auto() REJECTED = auto()

def __str__(self):
    return f'{self.name(self.value)}'

for state in State: print(state.name, state.value)`

Try it

How enum() auto works #

Technically, the auto() calls the _generate_next_value_() method to generate values for the members. Here’s the syntax of the _generate_next_value_() method:

_generate_next_value_(name, start, count, last_values)Code language: Python (python)

The _generate_next_value_() has the following parameters:

By default, the _generate_next_value_() generates the next number in a sequence of integers starting from one. However, Python may change this logic in the future.

It’s possible to override the _generate_next_value_() method to add a custom logic that generates unique values. If so, you need to place the _generate_next_value_() method before defining all the members.

The following shows how to override the _generate_next_value_() method to generate values for members by using their names:

`from enum import Enum, auto

class State(Enum): def generate_next_value(name, start, count, last_values): return name.lower()

PENDING = auto()
FULFILLED = auto()
REJECTED = auto()

for state in State: print(state.name, state.value)`Code language: Python (python)

Try it

Output:

PENDING pending FULFILLED fulfilled REJECTED rejectedCode language: Python (python)

Summary #

Was this tutorial helpful ?