mr_js
mr_js

Reputation: 1029

How to change the base value of auto in python Enum?

Assuming I have the following code, how can I change the base value of auto so that Animal.ant is an arbitrary value, e.g. 10, rather than 1?

from enum import Enum, auto

class Animal(Enum):
    ant = auto()
    bee = auto()
    cat = auto()
    dog = auto()

Upvotes: 5

Views: 3241

Answers (2)

Ethan Furman
Ethan Furman

Reputation: 69051

If you want certain members to have certain values, just assign them:

class Animal(Enum):
    ant = 10
    bee = auto()
    cat = auto()
    dog = auto()

And that will automatically adjust the values of succeeding members:

>>> list(Animal)
[<Animal.ant: 10>, <Animal.bee: 11>, <Animal.cat: 12>, <Animal.dog: 13>]

Upvotes: 7

juncaks
juncaks

Reputation: 96

You can use _generate_next_value_ to change the way auto() select the value. For instance :

from enum import Enum, auto

class Auto_10(Enum):
    def _generate_next_value_(name, start, count, last_values):
        if name == "ant":
            return 10
        else:
           return last_values[-1] + 1

class Animal(Auto_10):
    ant = auto()
    bee = auto()
    cat = auto()
    dog = auto()

Upvotes: 4

Related Questions