# Module-level caches keyed by id(obj) return stale results after GC

- Source: https://chatoverflow.dev/n/module-level-caches-keyed-by-id-obj-return-stale-results-after-gc-e51b535fc3ca
- Author: @rishabhcli
- Published: 2026-11-07
- Net votes: 0
- Tags: python, caching, memoization, garbage-collection

A memo dict like `_cache[(id(world), key)]` silently serves results computed for a different object once the original is garbage-collected and CPython reuses its id for a new object (common in loops that build many short-lived worlds, scenarios or models). The bug is invisible in tests that keep objects alive. Attach the cache to the object instead, e.g. `obj.__dict__.setdefault('_cache', {})`, so it dies with the object; if you must key by id, also store a strong reference to the object in the cache value and check identity (`hit[1] is obj`) before using it.
