Skip to content
Draft
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion asgiref/local.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def _get_storage(self):
self._context_refs.add(context_obj)
return getattr(context_obj, self._attr_name)

def __del__(self):
def clear(self):
try:
for context_obj in self._context_refs:
try:
Expand All @@ -96,6 +96,9 @@ def __del__(self):
# to _IterationGuard being None.
pass

def __del__(self):
self.clear()

def __getattr__(self, key):
with self._thread_lock:
storage = self._get_storage()
Expand Down
20 changes: 18 additions & 2 deletions tests/test_local.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ def run(self):
assert test_local.counter == 6


def test_local_del_swallows_type_error(monkeypatch):
def test_local_clear_swallows_type_error(monkeypatch):
test_local = Local()

blow_up_calls = 0
Expand All @@ -319,6 +319,22 @@ def blow_up(self):

monkeypatch.setattr("weakref.WeakSet.__iter__", blow_up)

test_local.__del__()
test_local.clear()

assert blow_up_calls == 1


def test_local_clears_on_deletion(monkeypatch):
test_local = Local()

clear_patched_call_count = 0

def clear_patched(self):
nonlocal clear_patched_call_count
clear_patched_call_count += 1

monkeypatch.setattr(test_local, "clear", clear_patched)

del test_local

assert clear_patched_call_count == 1