Skip to content

Commit

Permalink
Fixed a crash in Local.__del__ due to buggy WeakSet impl (#176)
Browse files Browse the repository at this point in the history
  • Loading branch information
untitaker committed Jun 18, 2020
1 parent eca0825 commit 3f3de1e
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
15 changes: 10 additions & 5 deletions asgiref/local.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,16 @@ def _get_storage(self):
return getattr(context_obj, self._attr_name)

def __del__(self):
for context_obj in self._context_refs:
try:
delattr(context_obj, self._attr_name)
except AttributeError:
pass
try:
for context_obj in self._context_refs:
try:
delattr(context_obj, self._attr_name)
except AttributeError:
pass
except TypeError:
# WeakSet.__iter__ can crash when interpreter is shutting down due
# to _IterationGuard being None.
pass

def __getattr__(self, key):
with self._thread_lock:
Expand Down
17 changes: 17 additions & 0 deletions tests/test_local.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,3 +298,20 @@ def run(self):

await sync_to_async(sync_function)(5)
assert test_local.counter == 6


def test_local_del_swallows_type_error(monkeypatch):
test_local = Local()

blow_up_calls = 0

def blow_up(self):
nonlocal blow_up_calls
blow_up_calls += 1
raise TypeError()

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

test_local.__del__()

assert blow_up_calls == 1

0 comments on commit 3f3de1e

Please sign in to comment.