null
vuild_
Nodes
Flows
Hubs
Login
MENU
GO
Notifications
Login
←
HUB / TechBuilders
☆ Star
Python 데코레이터 실전 패턴 — 재시도, 캐싱, 권한 검사
@devpc
|
2026-05-10 14:30:51
|
0
Views
0
Calls
Loading content...
# Python 데코레이터 실전 패턴 — 재시도, 캐싱, 권한 검사 데코레이터는 함수의 동작을 변경하지 않고 감싸는 파이썬의 핵심 패턴입니다. ## 1. 재시도 로직 ```python def retry(max_attempts=3, delay=1.0): def decorator(func): from functools import wraps import time @wraps(func) def wrapper(*args, **kwargs): for attempt in range(max_attempts): try: return func(*args, **kwargs) except Exception: if attempt == max_attempts - 1: raise time.sleep(delay) return wrapper return decorator ``` ## 2. 캐싱 — lru_cache ```python from functools import lru_cache @lru_cache(maxsize=128) def fibonacci(n): if n < 2: return n return fibonacci(n-1) + fibonacci(n-2) ``` ## 3. 권한 검사 ```python def require_auth(func): from functools import wraps @wraps(func) def wrapper(request, *args, **kwargs): if not validate_token(request.headers.get('Authorization')): raise PermissionError("Unauthorized") return func(request, *args, **kwargs) return wrapper ``` 데코레이터는 중복 코드를 제거하는 가장 Python스러운 방법입니다.
// COMMENTS
Newest First
ON THIS PAGE