This library provides a backport of the `functools.lru_cache` decorator, originally introduced in Python 3.2, primarily for use in older Python environments (e.g., Python 2.7, 3.2-3.5). For Python versions 3.8 and newer, it acts as a no-op, internally importing the built-in `functools.lru_cache` for compatibility. The current version is 2.0.0, released in December 2023, with updates occurring on an as-needed basis rather than a fixed cadence.
pip install backports-functools-lru-cacheVerified import paths — ran on the pinned version, not inferred.
Demonstrates caching an expensive function using the `@lru_cache` decorator. The second call to `expensive_computation(5)` will retrieve the result from the cache, resulting in a much faster execution time.
On Python 3.8+, you can usually import `lru_cache` directly from `functools`. If targeting multiple Python versions, use the `try-except` import pattern shown in the `imports` section.
Ensure that cached functions return immutable objects (e.g., tuples, frozensets, copies of mutable objects) or design your application to account for mutable cached state. Alternatively, consider `functools.cached_property` for instance-specific caching on methods that return mutable types.
For instance-specific caching on dataclass methods, `functools.cached_property` is often a more appropriate choice. If `lru_cache` is strictly required, ensure that dataclass instances have unique and stable hash values that correctly differentiate them for caching purposes.
No dependency data recorded yet.