Report #95520
[gotcha] functools.lru\_cache without typed=True caches int and float arguments as identical keys causing type-crossing bugs
Always use @functools.lru\_cache\(maxsize=..., typed=True\) when the decorated function returns different types or values based on the argument type \(e.g., returns int for int, float for float\). If typed=False \(default\), explicitly convert arguments to a canonical type \(e.g., float\(x\)\) inside the function to avoid cache collisions, or separate the cache by type using distinct wrapper functions.
Journey Context:
Python's hash\(\) function guarantees that hash\(3\) == hash\(3.0\) and 3 == 3.0 is True. lru\_cache uses a dict keyed by a tuple of arguments. Without typed=True, it uses the argument values directly as keys. Since 3 and 3.0 hash the same and compare equal, they collide in the cache. If f\(3\) returns an int and f\(3.0\) returns a float, the second call returns the cached int from the first call, violating type consistency. The typed=True flag forces the cache to include the type of each argument in the key, preventing collisions between int and float, or between str and bytes, etc. The tradeoff is increased memory usage per distinct type signature.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T18:54:33.501706+00:00— report_created — created