An expression is referentially transparent in a given context when replacing it with its value preserves the observable behavior. For a pure calculation over ordinary immutable values, substituting the result for a call can be safe. Substituting a value for a call that prints would remove the print. Identity, mutable results, exceptions, and timing can affect what counts as observable.
Memoization keeps results indexed by inputs so repeated calls can reuse them. Here lru_cache is a standard-library decorator: it wraps the function with a cache. The line @lru_cache(maxsize=4) applies the cache decorator when area is defined: it replaces the name area with a wrapped function. We explain decorators in Chapter 3. The demonstration uses a small cache; the function receives hashable integer arguments.
from functools import lru_cache
@lru_cache(maxsize=4)
def area(width, height):
return width * height
print(area(3, 7))
print(area(3, 7))
info = area.cache_info()
print(info.hits, info.misses)
21
21
1 1
The first call computes and stores the result; the second is a cache hit. The wrapper maintains hidden mutable cache state even though the calculated value is predictable. Cache keys must include all relevant inputs, and lru_cache requires hashable arguments. Do not cache an operation whose effect must occur on every call, or one that depends on changing hidden state without an invalidation strategy. Cached mutable results can be modified by callers and affect later callers. Caching uses memory and has overhead; measure whether it helps.