Skip to content

Instantly share code, notes, and snippets.

@rhcarvalho
Created June 28, 2021 11:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rhcarvalho/22467d851309675c737bcde02d9503aa to your computer and use it in GitHub Desktop.
Save rhcarvalho/22467d851309675c737bcde02d9503aa to your computer and use it in GitHub Desktop.
Python ContextVars don't propagate across exception handling boundaries
# coding: utf-8
import contextvars
import sys
v = contextvars.ContextVar('v')
v.set('global default')
def code():
print(f'before: v={v.get()}')
v.set('local code')
print(f'after: v={v.get()}')
1/0
def wrap_excepthook(old):
def excepthook(etype, value, traceback):
print(f'excepthook: v={v.get()}')
old(etype, value, traceback)
return excepthook
sys.excepthook = wrap_excepthook(sys.excepthook)
try:
contextvars.copy_context().run(code)
except Exception as e:
print(f'exception: v={v.get()}')
raise e
$ python3 ctx.py
before: v=global default
after: v=local code
exception: v=global default
excepthook: v=global default
Traceback (most recent call last):
File "/Users/rodolfo/ctx.py", line 27, in <module>
raise e
File "/Users/rodolfo/ctx.py", line 24, in <module>
contextvars.copy_context().run(code)
File "/Users/rodolfo/ctx.py", line 13, in code
1/0
ZeroDivisionError: division by zero
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment