Search code examples
pythonpython-3.xpython-decorators

Is it possible to decorate classes?


I know of function decorators and class method decorators.

But, is it also possible to decorate classes?


Solution

  • Yes, of course.

    A decorator is just a function taking a parameter. That parameter can be a class.

    #!/usr/bin/env python3
    
    def decorate(cls):
        print(cls)
        return cls
    
    @decorate
    class Foo: pass
    

    This code will work both in python2 and python3:

    $ python example.py
    __main__.Foo
    $ python3 example.py
    <class '__main__.Foo'>
    

    As for function decorators, a class decorator can return an arbitrary object. You probably want to return something behaving as the original class. You can also modify the class on the fly and return the class itself.

    If you are planning to have parameters for the decorator I suggest you this approach, which IMHO is the most natural (biased suggestion :D).