Decorators
Decorators alter a behaviour of a function. Example code:
def my_decorator(function):
def wrapper(*args, **kwargs):
# *args and **kwargs is important to pass the arguments and keyword arguments through the wrapper to the function
print("This line isn't a part of the original function")
return_val = function(*args, **kwargs)
print("This happens after function exec")
return return_val
@my_decorator
def test(random_string):
return f"Whatever: {random_string}"
print(test('yey'))
The output would be:
> This line isn't a part of the original function
> Whatever: yey
> This happens after function exec
Without the decorator, we would only get:
> Whatever: yey
You need to pass *args
and **kwargs
so that you get them after wrapping the function as well. PythonArgsKwargs
If you need to use return
, make sure to store the function output as a local variable before returning. If I were to just do return function(*args, **kwargs)
, the wrapper wouldn’t run in full.