[Python-ideas] class-only methods without using metaclasses

Nick Coghlan ncoghlan at gmail.com
Fri Mar 8 00:24:35 CET 2013


On Fri, Mar 8, 2013 at 9:02 AM, Greg Ewing <greg.ewing at canterbury.ac.nz> wrote:
> Nick Coghlan wrote:
>>
>> It's too much additional complexity to resolve a largely theoretical
>> problem.
>
>
> In Python 2 you could get class-only methods like this:
>
>    class Foo(object):
>
>       class __metaclass__(type):
>
>          def classmeth(cls):
>             ...
>
> I'm mildly disappointed that this can't be done any more
> in Python 3. Sometimes you need genuine metaclass methods,
> e.g. __xxx__ methods for a class rather than an instance.

You can still do that, you just have to define the metaclass in advance:

class FooMeta(type):
    def classmeth(cls):
        ...

class Foo(metaclass=FooMeta):
   ...

This is the price we pay for allowing metaclasses to customise the
namespace used to execute the class body in __prepare__.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list