Skip to content

Commit ce4e51a

Browse files
c-wilsonhynek
andcommitted
add unbind_threadlocal and try_unbind_threadlocal methods (#239)
* add unbind_threadlocal and try_unbind_threadlocal methods for "new" threadlocal context * match threadlocal.unbind to contextvars.unbind behavior Co-authored-by: Hynek Schlawack <[email protected]>
1 parent 971a621 commit ce4e51a

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

src/structlog/threadlocal.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,15 @@ def bind_threadlocal(**kwargs):
216216
_get_context().update(kwargs)
217217

218218

219+
def unbind_threadlocal(*keys):
220+
"""
221+
Tries to remove bound *keys* from threadlocal logging context if present.
222+
"""
223+
context = _get_context()
224+
for key in keys:
225+
context.pop(key, None)
226+
227+
219228
def _get_context():
220229
try:
221230
return _CONTEXT.context

tests/test_threadlocal.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
merge_threadlocal,
2121
merge_threadlocal_context,
2222
tmp_bind,
23+
unbind_threadlocal,
2324
wrap_dict,
2425
)
2526

@@ -316,3 +317,21 @@ def test_multiple_binds(self):
316317
assert {"a": 1, "b": 2, "c": 3} == merge_threadlocal(
317318
None, None, {"b": 2}
318319
)
320+
321+
def test_unbind_threadlocal(self):
322+
"""
323+
Test that unbinding from threadlocal works for keys that exist
324+
and does not raise error when they do not exist.
325+
326+
"""
327+
328+
clear_threadlocal()
329+
bind_threadlocal(a=234, b=34)
330+
assert {"a": 234, "b": 34} == merge_threadlocal_context(None, None, {})
331+
332+
unbind_threadlocal("a")
333+
334+
assert {"b": 34} == merge_threadlocal_context(None, None, {})
335+
336+
unbind_threadlocal("non-existing-key")
337+
assert {"b": 34} == merge_threadlocal_context(None, None, {})

0 commit comments

Comments
 (0)