[Python-Dev] What is the design purpose of metaclasses vs code generating decorators? (was Re: PEP 557: Data Classes)

Ronald Oussoren ronaldoussoren at mac.com
Fri Oct 20 11:48:18 EDT 2017

> On 14 Oct 2017, at 16:37, Martin Teichmann <lkb.teichmann at gmail.com> wrote:
>> Things that will not work if Enum does not have a metaclass:
>> list(EnumClass) -> list of enum members
>> dir(EnumClass)  -> custom list of "interesting" items
>> len(EnumClass)  -> number of members
>> member in EnumClass -> True or False
>> - protection from adding, deleting, and changing members
>> - guards against reusing the same name twice
>> - possible to have properties and members with the same name (i.e. "value"
>> and "name")
> In current Python this is true. But if we would go down the route of
> PEP 560 (which I just found, I wasn't involved in its discussion),
> then we could just add all the needed functionality to classes.
> I would do it slightly different than proposed in PEP 560:
> classmethods are very similar to methods on a metaclass. They are just
> not called by the special method machinery. I propose that the
> following is possible:
>>>> class Spam:
>     ...   @classmethod
>     ...   def __getitem__(self, item):
>     ...       return "Ham"
>>>> Spam[3]
>    Ham
> this should solve most of your usecases.

Except when you want to implement __getitem__ for instances as well :-). An important difference between @classmethod and methods on the metaclass is that @classmethod methods live in the same namespace as instance methods, while methods on the metaclass don’t.

I ran into similar problems in PyObjC: Apple’s Cocoa libraries use instance and class methods with the same name. That when using methods on a metaclass, but not when using something similar to @classmethod.  Because of this PyObjC is a heavy user of metaclasses (generated from C for additional fun). A major disadvantage of this is that tends to confuse smart editors. 


More information about the Python-Dev mailing list