Saturday, 11 September 2021

Python: Generate auto values to the enum members

Using ‘auto()’ function, you can assign auto generated values to the enum members.

 

autoValues.py

from enum import Enum, auto

class Day(Enum):
    MONDAY = auto()
    TUESDAY = auto()
    WEDNESDAY = auto()
    THURSDAY = auto()
    FRIDAY = auto()
    SATURDAY = auto()
    SUNDAY = auto()

for day in Day:
    print(day, ' -> ', day.value)

Output

 

Day.MONDAY  ->  1
Day.TUESDAY  ->  2
Day.WEDNESDAY  ->  3
Day.THURSDAY  ->  4
Day.FRIDAY  ->  5
Day.SATURDAY  ->  6
Day.SUNDAY  ->  7

 

If you assign any integer value to the enum member, succeeding enum member values are incremented by 1.

 

autoValues2.py

from enum import Enum, auto

class Day(Enum):
    MONDAY = auto()
    TUESDAY = auto()
    WEDNESDAY = 30
    THURSDAY = auto()
    FRIDAY = auto()
    SATURDAY = 111
    SUNDAY = auto()

for day in Day:
    print(day, ' -> ', day.value)

 

Output

Day.MONDAY  ->  1
Day.TUESDAY  ->  2
Day.WEDNESDAY  ->  30
Day.THURSDAY  ->  31
Day.FRIDAY  ->  32
Day.SATURDAY  ->  111
Day.SUNDAY  ->  112

 

Can I override the auto behavior?

Yes, by overriding the method ‘_generate_next_value_’, you can customize this behavior.

 

autoValues3.py

 

from enum import Enum, auto

class Day(Enum):
    def _generate_next_value_(name, start, count, last_values):
        return name
        
    MONDAY = auto()
    TUESDAY = auto()
    WEDNESDAY = 30
    THURSDAY = auto()
    FRIDAY = auto()
    SATURDAY = 111
    SUNDAY = auto()

for day in Day:
    print(day, ' -> ', day.value)

 

Output

Day.MONDAY  ->  MONDAY
Day.TUESDAY  ->  TUESDAY
Day.WEDNESDAY  ->  30
Day.THURSDAY  ->  THURSDAY
Day.FRIDAY  ->  FRIDAY
Day.SATURDAY  ->  111
Day.SUNDAY  ->  SUNDAY

 

 

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment