ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Decorators with parameters
    python/응용 2023. 10. 17. 17:17

     

    https://stackoverflow.com/a/25827070

     

    Transleates decorator without parameters

    @decorator
    def foo(*args, **kwargs):
        pass

    translates to 

    foo = decorator(foo)

     

    Transleates decorator with parameters

    @decorator_with_args(arg)
    def foo(*args, **kwargs):
        pass

    translates to

    foo = decorator_with_args(arg)(foo)

    decorator_with_args(arg) 은 function 을 파라미터로 받는 함수(decorator without parameters)가 되어야 한다.

     

    코드

    import functools
    
    
    def my_deco(msg):
        def inner(f):
            @functools.wraps(f)
            def wrapper(*args, **kwargs):
                print(f'Start {msg}')
                r = f(*args, **kwargs)
                print('End')
                return r
    
            return wrapper
    
        return inner
    
    
    @my_deco("Hello")
    def my_square(x):
        return x ** 2
    
    
    if __name__ == '__main__':
        result = my_square(3)
        print(result)
    
    
    # Start Hello
    # End
    # 9

     

     

    참고

    type signature in docorator functions

    import functools
    from time import perf_counter
    from typing import Callable, Any
    
    
    def benchmark(f: Callable[..., Any]) -> Callable[..., Any,]:
        @functools.wraps(f)
        def wrapper(*args: Any, **kwargs: Any):
            start_time = perf_counter()
            g = f(*args, **kwargs)
            end_time = perf_counter()
            run_time = end_time - start_time
            print(f"Execution of {f.__name__} took {run_time:.2f} second")
            return g
    
        return wrapper

    'python > 응용' 카테고리의 다른 글

    yield 활용 2  (0) 2023.11.15
    yield 활용 1  (0) 2023.11.15
    type hints Self type  (0) 2023.10.17
    Tips  (0) 2023.08.20
    Generators in python  (0) 2023.08.20

    댓글

Designed by Tistory.