Python functools

김신영·2025년 5월 13일

Python

목록 보기
6/10
post-thumbnail

functools고차 함수데코레이터 관련 유틸리티를 제공하는 표준 라이브러리 모듈

주요 함수 및 클래스

이름설명
functools.partial함수를 부분적으로 적용해서 인수를 고정한 새 함수를 생성
functools.partialmethod클래스 메서드에서 partial과 같은 역할
functools.reduce누적 함수 적용 (ex: 누적 덧셈 등)
functools.lru_cache함수 결과를 메모이제이션 (LRU 방식)
functools.cache제한 없는 메모이제이션 (Python 3.9+)
functools.cached_property속성 접근 시 계산 후 캐싱 (Python 3.8+)
functools.singledispatch단일 디스패치 제네릭 함수 구현
functools.singledispatchmethod클래스 메서드용 단일 디스패치 (Python 3.8+)
functools.update_wrapper데코레이터 함수의 메타데이터를 원본 함수로부터 복사
functools.wrapsupdate_wrapper를 간편하게 쓰도록 만든 데코레이터
functools.total_ordering하나의 비교 연산자만으로 모든 비교 연산 자동 생성
functools.cmp_to_keycmp 함수를 key 함수로 변환

사용 예제 및 내부 동작

partial

from functools import partial

def power(base, exponent):
    return base ** exponent

square = partial(power, exponent=2)
print(square(4))  # 16

동작: 일부 인수를 고정한 새로운 함수를 생성합니다.


partialmethod

from functools import partialmethod

class MyClass:
    def method(self, x, y):
        return x + y
    add_five = partialmethod(method, 5)

obj = MyClass()
print(obj.add_five(10))  # 15

동작: 메서드용 partial, 클래스에서 사용할 때 바인딩 처리도 함께 수행됩니다.


reduce

from functools import reduce

nums = [1, 2, 3, 4]
result = reduce(lambda x, y: x + y, nums)  # 10

동작: 리스트 등 반복 가능한 객체에 누적 함수 적용.


lru_cache

from functools import lru_cache

@lru_cache(maxsize=128)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

동작: 최근 사용된 항목을 캐싱 (maxsize 초과 시 가장 오래된 항목 제거).


cache

from functools import cache

@cache
def slow_fn(x):
    print(f"Computing {x}")
    return x * 2

동작: LRU 제한이 없는 메모이제이션 (Python 3.9+).


cached_property

from functools import cached_property

class Circle:
    def __init__(self, radius):
        self.radius = radius

    @cached_property
    def area(self):
        return 3.14 * self.radius ** 2

동작: 한번 계산된 후 값이 속성처럼 저장됨.


singledispatch

from functools import singledispatch

@singledispatch
def fun(arg):
    print("Default:", arg)

@fun.register(int)
def _(arg):
    print("Integer:", arg)

동작: 첫 번째 인자의 타입에 따라 함수가 동적으로 분기됨.


singledispatchmethod

from functools import singledispatchmethod

class Handler:
    @singledispatchmethod
    def handle(self, arg):
        print("Default", arg)

    @handle.register(int)
    def _(self, arg):
        print("Int", arg)

동작: 클래스 메서드에서 타입에 따라 분기.


update_wrapper / wraps

from functools import wraps

def my_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)
    return wrapper

동작: 원래 함수의 이름, docstring, signature 등을 유지.


total_ordering

from functools import total_ordering

@total_ordering
class Number:
    def __init__(self, value):
        self.value = value
    def __eq__(self, other):
        return self.value == other.value
    def __lt__(self, other):
        return self.value < other.value

동작: __eq__와 하나의 비교 연산만 있으면 나머지 자동 생성.


cmp_to_key

from functools import cmp_to_key

def compare(x, y):
    return x - y

sorted([5, 2, 9], key=cmp_to_key(compare))

동작: 옛 스타일 cmp 함수를 현대적 key 함수로 래핑.

profile
Hello velog!

0개의 댓글