Create a value lookup list for an enum

Viewed 464

I would like to add a lookup list in Enum as a static variable. The best I could do is

class Seed(IntEnum):
    HEARTS = 0
    DIAMONDS = 1
    SPADES = 2
    CLUBS = 3
    @staticmethod
    def value_list():
        Seed.list = [s.value for s in Seed]

and then in the code I have to do

Seed.value_list()

to initialize the variable list which in this way is not static but is the same for all the instances. Then I can use

Seed.list

Is there a way to do this?

2 Answers

You could write a class decorator:

def values_list(enum_cls):
    # create the values_list attribute and then return the class
    enum_cls.values_list = [member.value for member in enum_cls]
    return enum_cls

@values_list
class Seed(IntEnum):
    HEARTS = 0
    DIAMONDS = 1
    SPADES = 2
    CLUBS = 3

print(Seed.values_list)
# [0, 1, 2, 3]

You need to return the list of values:

from enum import IntEnum


class Seed(IntEnum):
    HEARTS = 0
    DIAMONDS = 1
    SPADES = 2
    CLUBS = 3

    @classmethod
    def values(cls):
        return [s.value for s in cls]

if __name__ == '__main__':

    print(Seed.values())

output:

[0, 1, 2, 3]
Related