Back to results for “Scope”
Python › Functions & Scope

How does Python evaluate default argument expressions ONLY ONCE at definition time, and what SAFE pattern exploits this for genuinely useful caching?

Advanced

Answer

Since a default value's expression is evaluated exactly once when the 'def' statement runs (not per-call), you can deliberately exploit this to CACHE an expensive computation as a function's own default argument — an unusual but valid technique for memoizing a value computed once and reused across all calls.
def expensive_computation():
    print("Computing...")
    return 42

def use_cached_value(value=expensive_computation()):  # runs ONCE, at def time
    return value

print(use_cached_value())  # 'Computing...' printed once, then 42
print(use_cached_value())  # just 42, NOT recomputed
Real-world example Deliberately caching an expensive, one-time initialization value as a function's default argument (an unusual but occasionally useful trick).

Common follow-ups: Why is this technique considered clever but potentially CONFUSING to other developers reading the code later?