# decorator factorydef repeat(times): def decorator(func): def wrapper(*args): for _ in range(times): result = func(*args) return result return wrapper return decorator@repeat(times=3)def greet(): print("Hello")greet()#ans: Hello (3 times)
import time# measure execution timedef timer(func): def wrapper(*args, **kwargs): start = time.time() result = func(*args, **kwargs) end = time.time() print(f"{func.__name__}: {end-start}s") return result return wrapper@timerdef slow(): time.sleep(1)
from functools import wraps# simple cachedef cache(func): cached = {} @wraps(func) def wrapper(*args): if args in cached: return cached[args] result = func(*args) cached[args] = result return result return wrapper@cachedef fibonacci(n): if n < 2: return n return fibonacci(n-1) + fibonacci(n-2)
# check permissiondef require_auth(func): def wrapper(*args, **kwargs): if not is_authenticated(): raise PermissionError() return func(*args, **kwargs) return wrapper@require_authdef sensitive_operation(): return "Secret"
# decorator with args?def repeat(n): def decorator(func): def wrapper(): for _ in range(n): func() return wrapper return decorator@repeat(2)def func(): print("Hi")func()#ans: Hi (twice)
# lru_cache?from functools import lru_cache@lru_cache(maxsize=128)def fib(n): if n < 2: return n return fib(n-1) + fib(n-2)#ans: built-in caching
# multiple decorators with args?@decorator1(arg1)@decorator2(arg2)def func(): pass#ans: both decorators get args
# decorator counting calls?def count_calls(func): def wrapper(*args): wrapper.calls += 1 return func(*args) wrapper.calls = 0 return wrapper@count_callsdef func(): passfunc()func.calls#ans: 1
# retry decorator?def retry(max_attempts): def decorator(func): def wrapper(*args): for attempt in range(max_attempts): try: return func(*args) except: if attempt == max_attempts-1: raise return wrapper return decorator
# validation decorator?def validate(type_): def decorator(func): def wrapper(arg): if not isinstance(arg, type_): raise TypeError() return func(arg) return wrapper return decorator@validate(int)def double(x): return x * 2
# property as decorator?class MyClass: @property def value(self): return 5#ans: property is a decorator
# classmethod as decorator?class MyClass: @classmethod def method(cls): pass#ans: classmethod is a decorator
# staticmethod as decorator?class MyClass: @staticmethod def method(): pass#ans: staticmethod is a decorator
# decorator preserving signature?from functools import wrapsdef decorator(func): @wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper#ans: preserves func signature
Google tag (gtag.js)