Search code examples
pythondecoratorpython-decoratorspep

Class-based decorators in Python - which PEP define syntax and semantic?


I open full list of PEPs: http://legacy.python.org/dev/peps/ and search by decorator keyword.

There are two PEPs with this keyword in title:

but they don't say anything about class-based decorators...

I wonder when and how class-based decorators introduced into Python.

UPDATE I talk about:

class NoArgsClassDecorator:

    def __init__(self, f):
        self.f = f

    def __call__(self):
        print('Inside %s.__call__(). You call %s()' % (self.__class__, self.f.__name__))
        self.f()
        print('Inside %s.__call__(). We finish %s()' % (self.__class__, self.f.__name__))

@NoArgsClassDecorator
def hello():
    print('hello')

Solution

  • Class-based decorators were included from the very start; quoting the Design Goals section of PEP 318:

    The new syntax should

    • work for arbitrary wrappers, including user-defined callables

    Emphasis mine.

    Classes are user-defined callables. Calling a class produces an instance; and like functions, class instances are just another object.

    The fact that you can make instances callable too by defining a __call__ method on the class, letting you replace functions with instances, has long been part if the language and never needed to be called out in the PEP.