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.wraps | update_wrapper를 간편하게 쓰도록 만든 데코레이터 |
functools.total_ordering | 하나의 비교 연산자만으로 모든 비교 연산 자동 생성 |
functools.cmp_to_key | cmp 함수를 key 함수로 변환 |
partialfrom functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
print(square(4)) # 16
동작: 일부 인수를 고정한 새로운 함수를 생성합니다.
partialmethodfrom 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, 클래스에서 사용할 때 바인딩 처리도 함께 수행됩니다.
reducefrom functools import reduce
nums = [1, 2, 3, 4]
result = reduce(lambda x, y: x + y, nums) # 10
동작: 리스트 등 반복 가능한 객체에 누적 함수 적용.
lru_cachefrom functools import lru_cache
@lru_cache(maxsize=128)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
동작: 최근 사용된 항목을 캐싱 (maxsize 초과 시 가장 오래된 항목 제거).
cachefrom functools import cache
@cache
def slow_fn(x):
print(f"Computing {x}")
return x * 2
동작: LRU 제한이 없는 메모이제이션 (Python 3.9+).
cached_propertyfrom functools import cached_property
class Circle:
def __init__(self, radius):
self.radius = radius
@cached_property
def area(self):
return 3.14 * self.radius ** 2
동작: 한번 계산된 후 값이 속성처럼 저장됨.
singledispatchfrom functools import singledispatch
@singledispatch
def fun(arg):
print("Default:", arg)
@fun.register(int)
def _(arg):
print("Integer:", arg)
동작: 첫 번째 인자의 타입에 따라 함수가 동적으로 분기됨.
singledispatchmethodfrom functools import singledispatchmethod
class Handler:
@singledispatchmethod
def handle(self, arg):
print("Default", arg)
@handle.register(int)
def _(self, arg):
print("Int", arg)
동작: 클래스 메서드에서 타입에 따라 분기.
update_wrapper / wrapsfrom functools import wraps
def my_decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper
동작: 원래 함수의 이름, docstring, signature 등을 유지.
total_orderingfrom 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_keyfrom functools import cmp_to_key
def compare(x, y):
return x - y
sorted([5, 2, 9], key=cmp_to_key(compare))
동작: 옛 스타일 cmp 함수를 현대적 key 함수로 래핑.