Created
March 8, 2023 08:19
-
-
Save OhadRubin/a591643cd68990c96cb229fd2affea8a to your computer and use it in GitHub Desktop.
a context manager to capture variables
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
import inspect | |
from contextlib import ContextDecorator | |
class VariableCapture(ContextDecorator): | |
def __enter__(self): | |
frame = inspect.currentframe().f_back | |
self.keys = {k for k,v in frame.f_locals.items() if k != 'self'} | |
return self | |
def __exit__(self, exc_type, exc_value, traceback): | |
if exc_type is None: | |
# no exception occurred, capture variables | |
frame = inspect.currentframe().f_back | |
self.variables = {k:v for k,v in frame.f_locals.items() if k not in self.keys} | |
# return False to propagate any exception that occurred | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment