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

Ethan Furman ethan at stoneleaf.us
Sat Oct 14 11:49:30 EDT 2017

On 10/14/2017 07:37 AM, Martin Teichmann 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.

The problem with your solution is you couldn't then have a __getitem__ for the instances -- it's an either/or situation. 
  The problem with PEP 560 is that it doesn't allow the class definition protections that a metaclass does.


More information about the Python-Dev mailing list