Skip to content

Instantly share code, notes, and snippets.

View KananMahammadli's full-sized avatar

Kanan Mahammadli KananMahammadli

View GitHub Profile
# let's write our parametrized timer decorator as parametrized class decorator
class class_timer:
def __init__(self, n):
self.n = n
def __call__(self, fn):
from time import perf_counter
def wrapper(*args, **kwargs):
total = 0
for _ in range(self.n):
# Passing the function that will be decorated during the initialization(non-parametrized class decorator)
class decorator:
def __init__(self, fn):
self.fn = fn
def __call__(self, *args, **kwargs):
print('Function decorated.')
return self.fn(*args, **kwargs)
def add(a, b, c=9):
@timer(15)
def fib_loop(n):
prev = 1
curr = 1
for i in range(n-2):
prev, curr = curr, prev + curr
return curr
print(fib_loop(5))
def timer(n):
def dec(fn):
from time import perf_counter
from functools import wraps
@wraps(fn)
def wrapper(*args, **kwargs):
total = 0
for _ in range(n):
start = perf_counter()
# timer decorator with additional parameter
def timer(fn, n):
from time import perf_counter
from functools import wraps
@wraps(fn)
def wrapper(*args, **kwargs):
total = 0
for _ in range(n):
start = perf_counter()
def timer(fn):
from time import perf_counter
from functools import wraps
# we will now create pass our fn function to wraps to create a decorator
dec = wraps(fn)
@dec
def wrapper(*args, **kwargs):
start = perf_counter()
result = fn(*args, **kwargs)
end = perf_counter()
# let's copy and paste our decorators
def counter(fn):
c = 0
from functools import wraps
@wraps(fn)
def wrapper(*args, **kwargs):
nonlocal c
c += 1
print(f'{fn.__name__} function called {c} times.')
return fn(*args, **kwargs)
def date_time(fn):
from datetime import datetime
from functools import wraps
@wraps(fn)
def wrapper(*args, **kwargs):
print(f'{fn.__name__} function run on: {datetime.today().strftime("%Y-%m-%d %H:%M:%S")}')
return fn(*args, **kwargs)
return wrapper
def add(a:int, b:int)->int:
def counter(fn):
c = 0
from functools import wraps
@wraps(fn)
def wrapper(*args, **kwargs):
nonlocal c
c += 1
print(f'{fn.__name__} function called {c} times.')
return fn(*args, **kwargs)
return wrapper
# using wrap function manually
# we import wrap from inside of the decorator
# so that whenever the decorator uses it will find wrap from enclosing scope
def counter(fn):
c = 0
from functools import wraps
def wrapper(*args, **kwargs):
nonlocal c
c += 1
print(f'{fn.__name__} function called {c} times.')