Python 데코레이터

유알·2024년 6월 3일
0

파이썬을 공부하다가 새로운 것을 알았는데 바로 이 데코레이터라는 녀석이다.
사실 별 다른 기능은 아니고, 우리가 흔히 쓰는 데코레이터 패턴 또는 프록시 패턴을 언어차원에서 지원하는 것으로 보인다.

사실 자바도 있다. 근데 좀 쓰기가 겁나 불편하다. spring에서 이를 추상화하고 간편화한 것도 지원해주긴 한다.

파이썬에서는 우리가 흔히 아는 어노테이션처럼 함수명을 붙여주면, 자동으로 데코레이터가 적용이 된다.

그냥 Spring AOP의 Around와 같다.

내가 단순하게 예제를 만들어 보았는데 바로 이해가 갈 것이다.

cache_store = dict()


# 함수를 인자로
def cachable(fun):
    def cache(msg):
        if msg in cache_store:
            return cache_store[msg]
        result = fun(msg)
        cache_store[msg] = result
        return result

    return cache


@cachable
def say_hello(msg):
    print("calculated")
    return "hello " + msg


say_hello("tom")
say_hello("tom")
say_hello("tom")
say_hello("tom")
say_hello("tom")
say_hello("tom")
say_hello("tom")
say_hello("tom")

실행 결과

calculated

단 한번 밖에 처리되지 않는다. 간결하구만

profile
더 좋은 구조를 고민하는 개발자 입니다

0개의 댓글