Proper Way of Using Enum Class Properties

Viewed 37

Has few .xlsx files storing the data I refer to. Added them up to Enum Class. Within the source code file I need to obtain some properties of the members of this Enum class, like file name here. Would the below code serve the problem well or there is an avenue to rework it in accordance with the best practices? Thank you!

from enum import Enum
class Data(Enum):
    TYPE_A = 1
    TYPE_B = 2
    TYPE_C = 3
    TYPE_D = 4
    TYPE_E = 5
    TYPE_F = 6
    TYPE_G = 7

    @property
    def file_name(cls):
        FILE_NAMES_DATA = (
            'TYPE_A.xlsx',
            'TYPE_B.xlsx',
            'TYPE_C.xlsx',
            'TYPE_D.xlsx',
            'TYPE_E.xlsx',
            'TYPE_F.xlsx',
            'TYPE_G.xlsx',
        )
        MAP_DATA = {
            member: file_name for member, file_name in zip(Data, FILE_NAMES_DATA)
        }
        return MAP_DATA[cls]


2 Answers

Instead of creating file names manually in FILE_NAMES_DATA, You can create them dynamically by defining a enum @property.

from enum import Enum

class Data(Enum):
    TYPE_A = 1
    TYPE_B = 2
    TYPE_C = 3
    TYPE_D = 4
    TYPE_E = 5
    TYPE_F = 6
    TYPE_G = 7
    @property
    def file_name(self):
        return self.name + '.xlsx'

for x in Data:
    print(x.file_name)    

Are the values 1-7 meaningless? Are the file names the same as the member names? ('TYPE_A', 'TYPE_B', etc.) In that case you can do:

class Data(Enum):
    #
    def _generate_next_value_(name, *args):
        return name
    #
    TYPE_A = auto()
    TYPE_B = auto()
    TYPE_C = auto()
    TYPE_D = auto()
    TYPE_E = auto()
    TYPE_F = auto()
    TYPE_G = auto()
    #
    @property
    def file_name(self):
        return self.value + '.xlsx'
Related