개발/python

파이썬 데코레이터의 원리 및 활용법: 코드 가독성과 효율성 향상 시키기

심집사 2023. 7. 8. 21:30

 

파이썬 데코레이터는 코드의 확장성과 재사용성을 개선하여 가독성과 효율성을 향상시키는 방법입니다. 이 글에서는 파이썬 데코레이터의 원리와 활용법에 대해 알아보겠습니다. 

 

데코레이터란?

  • 데코레이터는 함수나 메소드의 기능을 변경하지 않으면서 부가적인 처리를 추가할 수 있는 기법입니다. 파이썬에서는 기존 함수를 호출하는 것이 아닌, 함수를 감싸고 있는 새로운 함수를 호출함으로써 이 기법을 구현합니다.

데코레이터 작성하기

  • 데코레이터는 전달받은 함수를 개조하여 반환하는 함수를 사용해 작성할 수 있습니다. 예제를 통해 간단한 데코레이터를 만들어 보겠습니다.
python
def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()

출력 결과:

 
Something is happening before the function is called.
Hello!
Something is happening after the function is called.

데코레이터의 활용

  • 데코레이터는 다양한 상황에 유용하게 활용할 수 있습니다. 예를 들면, 실행 시간을 측정하거나 권한 확인 같은 인증 작업용으로 사용될 수 있습니다.

 

실행 시간을 측정하는 데코레이터 예제:

python
import time

def timer_decorator(func):
    def wrapper(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        end_time = time.time()
        print(f"{func.__name__} took {end_time - start_time:.2f} seconds to complete.")
        return result

    return wrapper

@timer_decorator
def slow_function():
    time.sleep(2)

slow_function()

출력 결과:

 
slow_function took 2.00 seconds to complete.

 

 

결론

  • 파이썬 데코레이터를 통해 코드의 확장성과 재사용성을 개선하고 가독성과 효율성을 높일 수 있습니다. 이 글을 통해 파이썬 데코레이터의 원리와 활용법을 이해하셨기를 바랍니다.