Decorators

Fundamentals

Python Decorators in 15 Minutes

Say we have

def f1():
    print("called f1")

f1
>> <function f1 at 0x008EEDF8>

f1 is actually an object at some memory address in Python. So we can actually pass functions around (since they are objects) into functions, store it in variables, etc.

def f1():
    print("called f1")

def f2(f):
    f()

f2(f1)
>> called f1

Example

To remember easier, remember decorator is a function that wraps a function and takes in the function below it as an argument.

Decorating Functions with Arguments

We use args and kwargs because we have no idea what arguments will be passed into the function. So this allows us to have any arguments or number of arguments in the function.

Returning values from decorators

Decorators with Arguments

https://www.artima.com/weblogs/viewpost.jsp?thread=240845#decorator-functions-with-decorator-arguments

Making a class a custom decorator

See built in methods: __call__ and functools: wraps for prerequisite knowledge.

Equivalence

https://stackoverflow.com/questions/38516426/apply-different-decorators-based-on-a-condition

A decorator can also be called as a function. @decorator is equivalent to decorator(func) and @decorator(args) to decorator(args)(func). So you could return the value of those function returns conditionally in your decorator. Here is an example below:

Last updated

Was this helpful?