사용자 도구

사이트 도구


python:decorator

차이

문서의 선택한 두 판 사이의 차이를 보여줍니다.

차이 보기로 링크

다음 판
이전 판
python:decorator [2016/05/30 23:39] – 만듦 rex8312python:decorator [2024/03/23 02:42] (현재) – 바깥 편집 127.0.0.1
줄 1: 줄 1:
 ====== Python: Decorator ====== ====== Python: Decorator ======
 +
 +===== 함수 실행시간 측정 =====
 +
 +<code python>
 +from functools import wraps
 +
 +
 +def elapsed_time(func):
 +    import time
 +    
 +    @wraps(func)
 +    def wrapped(*args, **kwargs):
 +        start_time = time.perf_counter()
 +        returns = func(*args, **kwargs)
 +        end_time = time.perf_counter()
 +        print('{} -> elased time: {:.3f}'.format(func.__name__, end_time - start_time))
 +        return returns
 +    
 +    return wrapped
 +  
 +  
 +@elapsed_time
 +def test_sleep(t):
 +    import time
 +    time.sleep(t)
 +    return True
 +</code>
 +
 +  
 +====== Logger wrapping ======
 +
 +terminal 창의 마지막 줄에 elapsed time을 계속 표시함
 +
 +<code python>
 +def logger_info_with_state_bar(func):
 +
 +    global start_time
 +
 +    def wrapped(msg):
 +        columns = os.get_terminal_size().columns
 +        print(Fore.RESET + Back.RESET + ' ' * (columns - 1), end='\r')
 +        func(msg)
 +        status = 'elapsed time: {}'.format(time.time() - start_time)
 +        if len(status) < (columns - 1):
 +            status += ' ' * (columns - len(status) - 1)
 +        print(Back.GREEN + Fore.BLACK + status + Fore.RESET + Back.RESET, end='\r')
 +
 +    return wrapped
 +
 +logger.info = logger_info_with_state_bar(logger.info)
 +</code>
 +  
 +===== Decorator with parameters =====
 +
 +<code python>
 +def decorator_factory(argument):
 +    def decorator(function):
 +        def wrapper(*args, **kwargs):
 +            funny_stuff()
 +            something_with_argument(argument)
 +            result = function(*args, **kwargs)
 +            more_funny_stuff()
 +            return result
 +        return wrapper
 +    return decorator
 +    
 +# https://stackoverflow.com/questions/5929107/decorators-with-parameters
 +</code>
 +
 +===== 튜토리얼 =====
  
   * http://www.hanbit.co.kr/network/category/category_view.html?cms_code=CMS5689111564   * http://www.hanbit.co.kr/network/category/category_view.html?cms_code=CMS5689111564
python/decorator.1464651563.txt.gz · 마지막으로 수정됨: (바깥 편집)