Created
June 28, 2021 11:50
-
-
Save rhcarvalho/22467d851309675c737bcde02d9503aa to your computer and use it in GitHub Desktop.
Python ContextVars don't propagate across exception handling boundaries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ 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