Python Decorator
Exemplares de decoradores.
from functools import wraps
def timer(function):
# Closures
from datetime import datetime
@wraps(function)
def wrapper(*args, **kwargs):
# Before function
print(f'Funtion name: {function.__name__}')
start = datetime.now()
result = function(*args, **kwargs)
# After function
end = datetime.now()
print(f'Time to run: {end - start}')
return result
return wrapper
@timer
def example_1(x, y):
return x + y
def decorator_2(arg):
def wrap(func):
@wraps(func)
def wrapper(*args, **kwargs):
# You can use the arguments passed by decorator however you like
# Before function
result = func(*args, **kwargs)
# After function
return result
return wrapper
return wrap
@decorator_2(arg='xpto')
def example_2(x, y):
return x + y
def decorator_3(function):
# Closures: share scope with in inner functions or classes
count = 0
@wraps(function)
def wrapper(*args, **kwargs):
# nonlocal is needed if you want to re-assign the value of a variable
# that is in the scope of the closure
nonlocal count
count += 1
print(count)
return function(*args, **kwargs)
return wrapper
@decorator_3
def example_3(x, y):
return x + y