Metaclasses and classproperties

Eko palypse ekopalypse at gmail.com
Tue Sep 10 11:29:04 EDT 2019


I'm fairly new when it comes to metaclass programming and therefore the
question whether the following makes sense or not.

The goal is to have two additional class properties which return a
dictionary name:class_attribute and value:class_attribute for an IntEnum class
and after reading about it I came to the conclusion that the following code
might do what I want, and it does do the job BUT does it make sense also?

Meaning, my ultimate goal would be to be able to decide myself
if this is a good or bad idea doing this, so what do I need to 
read/understand in order to achieve such a goal.


from enum import EnumMeta, IntEnum

class EnhancedIntEnum(EnumMeta):
    @property
    def names(cls):
        return {k: v for k, v in cls.__members__.items()}

    @property
    def values(cls):
        return {v.value: v for k, v in cls.__members__.items()}


class Ordinal(IntEnum, metaclass=EnhancedIntEnum):
    NORTH = 0
    SOUTH = 1
    EAST = 2
    WEST = 3

print(Ordinal.names)
print(Ordinal.values)

Thank you
Eren



More information about the Python-list mailing list