Decorators - AndrewMZ6/python_cheat_sheet GitHub Wiki

@decorator
def function():
    pass

is the same as

function = decorator(function)

decorator adds functionality and returns new function instead of the old fucntion

Simple decorator

def decorator(func):
	def wrapper(x):
		print(f"Hi, I'm wrapper function :)")
		func(x)
	return wrapper
	
@decorator
def myfunction(x):
	print(f"x = {x}")

myfunction('some string')

output:

Hi, I'm wrapper function :)
x = some string

Parametrized decorator

def parametrized(*args, **kwargs):
	def decorator(func):
		def wrapper(*args2):
			print(f'decotrator arguments = {args}')
			print(f'decotrator keyword arguments = {kwargs}')
			func(args2)
		return wrapper
	return decorator

@parametrized(75, 'hello', [1, 2, 3], type = 5)
def myfunction(x):
	print(f"Hi x = {x}")

myfunction(1, 2)

output:

decotrator arguments = (75, 'hello', [1, 2, 3])
decotrator keyword arguments = {'type': 5}
Hi x = (1, 2)