Decorators specially built for python to beautify programming experience. It allows you to add new functionality to an existing object without modifying its structure. decorators denote like that: @deco
Now we will see a example of decorators, we will find out a print execution time using decorators. see below example:
#performance decorator
from time import time
def performance(fn):
def wrapper(*args, **kwargs):
t1 = time()
result = fn(*args, **kwargs)
t2 = time()
print(f'took {t2-t1}')
return result
return wrapper
@performance //performance decorator called
def long_time():
for i in range(10000):
i*5
long_time()
user1 = {
'name': 'Sorna',
'valid': True
}
def authenticated(fn):
def wrapper(*args, **kwargs):
if args[0]['valid']:
return fn(*args, **kwargs)
return wrapper
@authenticated
def message_friends(user):
print('message has been sent')
message_friends(user1)
