Question

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')
Was it helpful?

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top