[Python] Decorator와 functools의 wraps
작성일 : 2024-09-23
Python에는 Decorator라는 기능이 있다.
Decorator하면 '장식하다', '꾸미다'와 같은 의미가 생각나지만
기능적으로는 외장 라이브러리 functools의 wrap(wrap도 decorator)이 더 직관적인 이름인 것 같다.
말 그대로 감싸는 역할을 한다.
어떨 때 쓰이는가?
내가 이해한 바로는, 완성된 함수들에 반복적으로 같은 기능을 적용하고 싶을 때 쓴다.
흥미로운 건 디자인 패턴 측면의 기능이라는 것이다.
아래 예시를 보자.
Decorator
class CallpsedTimeDecorator:
from datetime import datetime
def __init__(self, f):
self.func = f
def __call__(self, *args, **kwargs):
start_time = datetime.now()
self.func(*args, **kwargs)
end_time = datetime.now()
callapsed_time = start_time - ed_time
print(f'callapsed_time: {callapsed_time}')'
class MainClass:
@CallpasedTimeDecorator
def main_function1():
print('main function1')
@CallpasedTimeDecorator
def main_function2():
print('main function2')
@CallpasedTimeDecorator
def main_function3():
print('main function3')
my = MainClass()
my.main_function1()
my.main_function2()
my.main_function3()
c.f.
python decorator (데코레이터) 어렵지 않아요
python decorator (데코레이터) 어렵지 않아요
Python decorator (데코레이터) Python 으로 작성된 Opensource 의 코드들을 보다 보면, 아래와 같이 @ 로 시작하는 구문 들을 볼 수 있다. @decorator_def function(): print "what is decorator?" decorator를 한마디로 얘기
bluese05.tistory.com
functools
이외에도 외장 라이브러리 functools의 wraps 메소드가 있다.
간단히 말하면 decorator의 단점을 보완한 업그레이드된 decorator이다.
공식문서를 참고해서 정리하자면 다음과 같다.
functools.wraps는 update_wrapper()를 호출하기 위한 편의 함수로, 내부적으로는 update_wrapper() 함수를 호출한다.
이를 통해 데코레이터 함수가 원래 함수의 메타데이터(예: 함수명, docstring, annotations 등)를 그대로 유지하도록 한다.
데코레이터 함수를 쓰면 원래 함수가 다른 함수로 감싸지게 되어, 이 과정에서 원래 함수의 이름, docstring, annotations 등 중요한 메타 데이터가 사라질 수 있다. 그렇게 되면 디버깅과 문서화가 불리해질 수 있다. 이를 보완하기 위해 쓰이는 것이 wraps이다.
여기서 update_wrapper()는 무엇일까?
데코레이터가 원래 함수의 속성(예: __name__, __doc__)을 복사하는 일을 한다.
즉 wraps를 쓰는 이유는 update_wrapper()의 기능을 위해 쓰는 것이다.
wraps는 간단한 약어라고 생각하면 된다.
c.f.
functools — Higher-order functions and operations on callable objects
functools — Higher-order functions and operations on callable objects
Source code: Lib/functools.py The functools module is for higher-order functions: functions that act on or return other functions. In general, any callable object can be treated as a function for t...
docs.python.org
밑에 어떤 한국 블로그 통해서 알게 된 블로그 원본 글인데, 직접 읽는 게 더 낫다.
난 번역투가 더 어려운 것 같다.
print말고 html 태그 형식으로도 쓰는 방법이 있어 기재해본다.
A guide to Python's function decorators
A guide to Python's function decorators
Python is rich with powerful features and expressive syntax. One of my favorites is decorators. In the context of design patterns, decorators dynamically alter the functionality of a function, method or class without having to directly use subclasses. This
www.thecodeship.com
돌아보며
나는 아직 익숙하지 않으니 간단하게 print 반복할 때나
위에 예시처럼 callapsed time(경과시간) 측정할 때 써버릇해야겠다.
참고로 callapsed time은 병렬처리나 동시성처리를 통해 시간 단축을 얼마나 했는지 확인하는 용으로 start time과 end time의 차로 구한다.
그리고 이런 데코레이터의 특징 때문에 중첩함수, Closure라는 개념도 발견했다.
나중에 차근차근 알아보도록 하자.