Search code examples
pythondecorator

What is a decorator used for?


Many documents online concern about the syntax of decorator. But I want to know where and how is the decorator used? Is the decorator just used to execute extra codes before and after the decorated function? Or maybe there is other usage?


Solution

  • The decorator syntax is powerful:

    @decorator
    def foo(...):
        ...
    

    is equivalent to

    def foo(...):
        ...
    foo = decorator(foo)
    

    That means that decorators can do basically anything -- they don't have to have any relation to the decorated function! Examples include:

    • memoising a recursive function (functools.lru_cache)
    • logging all calls to a function
    • implementing the descriptor functionality (property)
    • marking a method as static (staticmethod)