[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Metaclasses and classproperties

Eko palypse wrote:

> 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.

My objections have nothing to do with metaclass technicalities, but

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

this is basically a writeable copy of __members__. Using


directly should be better in most cases, and if you really need a copy




is pretty clear and concise enough. 

If you want to convert a str use Ordinal["WEST"] rather than 

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

Again, I don't see the use case; if you want to convert an int to your 
`Ordinal`, just use the constructor


> class Ordinal(IntEnum, metaclass=EnhancedIntEnum):
>     NORTH = 0
>     SOUTH = 1
>     EAST = 2
>     WEST = 3
> print(Ordinal.names)
> print(Ordinal.values)
> Thank you
> Eren