Python functools ライブラリ完全ガイド
Python 標準ライブラリの functools は、関数プログラミングをより効果的に行うためのツールを提供します。本記事では、functools の主要な機能とその活用方法について詳しく解説します。
1. functools ライブラリの概要
functoolsは、関数を操作・最適化するためのツールを提供します。- 高階関数(関数を引数や戻り値として扱う関数)を簡単に扱うことができます。
- キャッシュ、部分適用、比較関数、デコレーターの作成などに役立ちます。
インストール方法
functools は Python の標準ライブラリなので、追加のインストールは不要です。
import functools
import functools
import time
@functools.lru_cache(maxsize=3)
def slow_function(n):
time.sleep(2) # 処理を遅らせる
return n * n
print(slow_function(2)) # 計算に2秒かかる
print(slow_function(2)) # キャッシュされて即座に返される
import functools
def power(base, exponent):
return base ** exponent
square = functools.partial(power, exponent=2)
print(square(3)) # 9
import functools
def my_decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print("実行前")
result = func(*args, **kwargs)
print("実行後")
return result
return wrapper
@my_decorator
def say_hello():
"この関数は挨拶をする"
print("Hello!")
print(say_hello.__name__) # 'say_hello' (デコレーターを使用しても関数名が保持される)
import functools
import operator
numbers = [1, 2, 3, 4]
result = functools.reduce(operator.mul, numbers)
print(result) # 24(1 * 2 * 3 * 4)
import functools
@functools.total_ordering
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
return self.age == other.age
def __lt__(self, other):
return self.age < other.age
p1 = Person("Alice", 30)
p2 = Person("Bob", 25)
print(p1 > p2) # True
import functools
@functools.lru_cache(maxsize=3)
def square(n):
return n * n
square(2)
square.cache_clear() # キャッシュをクリア
import functools
def compare(x, y):
return x - y
sorted_list = sorted([5, 3, 8, 1], key=functools.cmp_to_key(compare))
print(sorted_list) # [1, 3, 5, 8]
import functools
class Calculator:
def power(self, base, exponent):
return base ** exponent
square = functools.partialmethod(power, exponent=2)
calc = Calculator()
print(calc.square(4)) # 16
import functools
@functools.cache
def factorial(n):
return n * factorial(n - 1) if n else 1
print(factorial(5)) # 120
import functools
def decorator(func):
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return functools.update_wrapper(wrapper, func)
@decorator
def say_hello():
"挨拶をする関数"
print("Hello!")
print(say_hello.__doc__) # 挨拶をする関数