3.1. About Decorators

3.1.1. What are decorators?

  • Introduced in PEP 318 - Decorators for Functions and Methods in 2003 for Python 2.4

  • Decorator is an object, which takes another object as it's argument

  • Decorators can:

    • Do things before call

    • Do things after call

    • Modify arguments

    • Modify returned value

    • Avoid calling

    • Modify globals

    • Add or change metadata

3.1.2. Types of decorators

By type:

  • Function Decorators

  • Class Decorators

By wrapper type:

  • Wrapper function

  • Wrapper class

  • Wrapper method (__call__)

By decorated object:

  • Decorating function

  • Decorating class

  • Decorating methods

By number of arguments:

  • Without arguments

  • With arguments

3.1.3. Function Decorate Function

@decorator
def my_function(*args, **kwargs):
    pass

3.1.4. Function Decorate Method

class MyClass:
    @decorator
    def my_method(self, *args, **kwargs):
        pass

3.1.5. Function Decorate Class

@decorator
class MyClass:
    pass

3.1.6. Class Decorate Function

@Decorator
def my_function(*args, **kwargs):
    pass

3.1.7. Decorator with arguments

Listing 3.100. Decorator with arguments
@decorator(a, b)
def my_function(*args, **kwargs):
    pass