Metaclasses and classproperties

Peter Otten __peter__ at web.de
Tue Sep 10 12:42:59 EDT 2019


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

Ordinal.__members__

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

Ordinal.__members__.copy()

or

dict(Ordinal.__members__)

is pretty clear and concise enough. 

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

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

Ordinal(some_int)

> 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