Skip to content

Commit 1c972de

Browse files
committed
fix: stop cached_ref from stacking finalizers on repeat calls
The first call to `cached_ref(obj)` inserts a weakref into `GLOBAL_REFS` and attaches a `weakref.finalize` callback to evict it on GC. Every subsequent call returned the cached weakref correctly, but also attached another `finalize` to the same object, leaking one finalize per call. Move the `finalize` attach inside the `if obj_id not in GLOBAL_REFS:` branch so it runs exactly once per cached object. Repeated callers no longer accumulate weakref entries; `weakref.getweakrefcount(obj)` stays flat across calls.
1 parent ec313ea commit 1c972de

2 files changed

Lines changed: 41 additions & 3 deletions

File tree

‎src/django_components/util/weakref.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@ def cached_ref(obj: T) -> ReferenceType[T]:
1616
obj_id = id(obj)
1717
if obj_id not in GLOBAL_REFS:
1818
GLOBAL_REFS[obj_id] = ref(obj)
19-
20-
# Remove this entry from GLOBAL_REFS when the object is deleted.
21-
finalize(obj, lambda: GLOBAL_REFS.pop(obj_id, None))
19+
# Remove this entry from GLOBAL_REFS when the object is deleted.
20+
# Attached only on first insertion - repeated calls must not stack finalizers.
21+
finalize(obj, lambda: GLOBAL_REFS.pop(obj_id, None))
2222

2323
return GLOBAL_REFS[obj_id]

‎tests/test_util_weakref.py‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import gc
2+
import weakref
3+
4+
from django_components.util.weakref import GLOBAL_REFS, cached_ref
5+
6+
7+
class _Dummy:
8+
pass
9+
10+
11+
class TestCachedRef:
12+
def test_returns_same_reference_on_repeated_calls(self):
13+
obj = _Dummy()
14+
r1 = cached_ref(obj)
15+
r2 = cached_ref(obj)
16+
assert r1 is r2
17+
assert r1() is obj
18+
19+
def test_does_not_stack_finalizers_on_repeated_calls(self):
20+
# `cached_ref` previously attached a new `weakref.finalize` on every
21+
# call, even on cache hit. Each `finalize` registers a weak reference
22+
# to the target, so the leak shows up as a growing
23+
# `weakref.getweakrefcount(obj)`.
24+
obj = _Dummy()
25+
cached_ref(obj)
26+
baseline = weakref.getweakrefcount(obj)
27+
for _ in range(20):
28+
cached_ref(obj)
29+
assert weakref.getweakrefcount(obj) == baseline
30+
31+
def test_global_refs_entry_removed_on_collection(self):
32+
obj = _Dummy()
33+
cached_ref(obj)
34+
obj_id = id(obj)
35+
assert obj_id in GLOBAL_REFS
36+
del obj
37+
gc.collect()
38+
assert obj_id not in GLOBAL_REFS

0 commit comments

Comments
 (0)