Skip to content

Instantly share code, notes, and snippets.

@OhadRubin
Created March 8, 2023 08:19
Show Gist options
  • Save OhadRubin/a591643cd68990c96cb229fd2affea8a to your computer and use it in GitHub Desktop.
Save OhadRubin/a591643cd68990c96cb229fd2affea8a to your computer and use it in GitHub Desktop.
a context manager to capture variables
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