diff --git a/asgiref/local.py b/asgiref/local.py index 17314d4e..95650e22 100644 --- a/asgiref/local.py +++ b/asgiref/local.py @@ -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: @@ -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() diff --git a/tests/test_local.py b/tests/test_local.py index 035c99f9..330cc12d 100644 --- a/tests/test_local.py +++ b/tests/test_local.py @@ -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 @@ -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) + + test_local.__del__() + + assert clear_patched_call_count == 1