Skip to content

Instantly share code, notes, and snippets.

@Farrukhraz
Last active May 10, 2020 16:51
Show Gist options
  • Save Farrukhraz/a8bd8ddb544028c1719edaa60d25856b to your computer and use it in GitHub Desktop.
Save Farrukhraz/a8bd8ddb544028c1719edaa60d25856b to your computer and use it in GitHub Desktop.
All given functions (decorators) should be in the separate module: decorators.py; Thnks for this article "https://proglib.io/p/vse-chto-nuzhno-znat-o-dekoratorah-python-2020-05-09#dark-theme-toggler"
import functools
def debug(func):
@functools.wraps(func)
def wrapper_debug(*args, **kwargs):
args_repr = [repr(a) for a in args]
kwargs_repr = [f"{k}={v!r}" for k, v in kwargs.items()]
signature = ", ".join(args_repr + kwargs_repr)
print(f"Вызываем {func.__name__}({signature})")
value = func(*args, **kwargs)
print(f"{func.__name__!r} возвращает {value!r}")
return value
return wrapper_debug
# Wrapping imported function
math.factorial = debug(math.factorial)
# Reapeats decorated function 'n' times.
import functools
def repeat(n):
def decorator_repeat(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for _ in range(num_times):
value = func(*args, **kwargs)
return value
return wrapper
return decorator_repeat
@repeat(num_times=4)
def great(name):
print(f"Привет {name}")
# Base decorator schema for more complex ones
# @functools.wraps(func); Let us save all meta data of original function
import functools
def decorator(func):
@functools.wraps(func)
def wrapper_decorator(*args, **kwargs):
# Что-то делаем до
value = func(*args, **kwargs)
# Что-то делаем после
return value
return wrapper_decorator
import time
def slow_down(func):
"""Ждёт 1 секундеу, прежде чем вызвать переданную функцию"""
@functools.wraps(func)
def wrapper_slow_down(*args, **kwargs):
time.sleep(1)
return func(*args, **kwargs)
return wrapper_slow_down
# 'timer' decorator. Count the spent time for executing 'func'
# use 'timeit' for more accurate time measurements
import functools
import time
def timer(func):
"""Выводит время выполнения декорируемой функции"""
@functools.wraps(func)
def wrapper_timer(*args, **kwargs):
start_time = time.perf_counter()
value = func(*args, **kwargs)
end_time = time.perf_counter()
run_time = end_time - start_time
print(f"Функция {func.__name__!r} выполнена за {run_time:.4f} с")
return value
return wrapper_timer
# Example
@timer
def waste_some_time(num_times):
for _ in range(num_times):
sum([i**2 for i in range(10000)])
import random
PLUGINS = dict()
def register(func):
"""Регистрирует функцию как плагин"""
PLUGINS[func.__name__] = func
return func
@register
def say_hello(name):
return f"Привет, {name}!"
@register
def be_awesome(name):
return f"Привет, {name}, классно быть вместе!"
def randomly_greet(name):
greeter, greeter_func = random.choice(list(PLUGINS.items()))
print(f"Используется {greeter!r}")
return greeter_func(name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment