functools32
functools32 is a backport of the `functools` standard library module from Python 3.2.3, designed for use with Python 2.7 and PyPy. Its primary purpose is to provide features like `lru_cache` (Least-recently-used cache decorator) to older Python environments that lack them natively. The library saw its last release in July 2015 and is no longer actively maintained, as its features are standard in Python 3+ versions.
Warnings
- breaking functools32 is strictly for Python 2.7 and PyPy. Attempting to install or use it on Python 3 will lead to errors, as the functionality it provides is already built into Python 3's standard `functools` module.
- deprecated The entire library is considered deprecated due to Python 2.7 reaching its end-of-life and the complete integration of its features into modern Python 3. No further development or maintenance is expected.
- gotcha Using mutable arguments (e.g., lists, dictionaries) with `lru_cache` will result in a `TypeError: unhashable type` because cached function arguments must be hashable to serve as dictionary keys.
- gotcha While `lru_cache` is thread-safe for basic usage, a race condition can occur where the decorated function might be called more than once by different threads if an initial call has not yet completed and cached its result. `cached_property` in newer `functools` also has similar considerations.
Install
-
pip install functools32
Imports
- lru_cache
from functools32 import lru_cache
from functools import lru_cache
- partial
from functools import partial
Quickstart
import sys
# This library is only for Python 2.7/PyPy.
# For modern Python, functools.lru_cache is built-in.
if sys.version_info.major < 3:
import functools
from functools import lru_cache
import time
@lru_cache(maxsize=128)
def fibonacci(n):
if n < 2:
return n
return fibonacci(n - 1) + fibonacci(n - 2)
print(f"Calculating fibonacci(30) on Python {sys.version_info.major}.{sys.version_info.minor}...")
start = time.time()
result = fibonacci(30)
end = time.time()
print(f"fibonacci(30) = {result}, took {end - start:.4f} seconds")
print(f"Cache info: {fibonacci.cache_info()}")
else:
print(f"functools32 is not needed on Python {sys.version_info.major}.{sys.version_info.minor}. Use built-in functools.")