Search code examples
pythonenumsdecorator

How can I decorate my enum when using FunctionalAPI?


from enum import IntEnum, unique

# @unique <- decorator syntax does not work for variable assignment
Weekday = IntEnum("Weekday", "sun mon tue wed thu fri sat", start=0)

Obviously one could just write this out as a class but I wonder if this is possible with the syntax as shown above.

https://docs.python.org/3/library/enum.html#functional-api


Solution

  • You can use it as a function instead of a decorator.

    Weekday = unique(IntEnum("Weekday", "sun mon tue wed thu fri sat", start=0))
    

    However, it's not necessary: the use of Functional API guarantees that every value will be unique. This is done in _generate_next_value_ in enum.py.

    Creating IntEnum invokes __call__

    def __call__(cls, value, names=None, *, ..., start=1):
    

    which invokes cls._create_

    def _create_(cls, class_name, names, *, ..., start=1):
    

    which calls _generate_next_value_ in a loop to assign values in increasing order

    for count, name in enumerate(original_names):
        first_enum._generate_next_value_(name, start, count, last_values[:])