Created
April 22, 2017 15:15
-
-
Save tkf/dc4b368d52a55d249f4e32adfaf6fd09 to your computer and use it in GitHub Desktop.
Capture the local variables of a function upon exception.
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
from contextlib import contextmanager | |
import sys | |
@contextmanager | |
def capturing_locals(depth=1): | |
""" | |
Capture the local variables of a function upon exception. | |
>>> def fun(): | |
... x = 1 | |
... assert 0 | |
... y = 2 | |
... | |
>>> with capturing_locals() as midway: | |
... fun() | |
... | |
Traceback (most recent call last): | |
... | |
AssertionError | |
>>> midway | |
{'x': 1} | |
""" | |
midway = {} | |
try: | |
yield midway | |
except Exception: | |
_type, _value, tb = sys.exc_info() | |
for _ in range(depth + 1): # +1 to skip @contextmanager | |
tb = tb.tb_next | |
midway.update(tb.tb_frame.f_locals) | |
del tb | |
raise |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment