Forked from CodeByAidan/log_variables_in_function.py
Created
August 13, 2025 12:42
-
-
Save datavudeja/2fca1410f74d2a5e5415d9ef5efefd20 to your computer and use it in GitHub Desktop.
Decorator that prints the variables in a function (being wrapped) values as they change. Pretty nifty.
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 sys | |
| from functools import wraps | |
| from typing import Any, Callable, Optional, TypeVar | |
| F = TypeVar("F", bound=Callable[..., Any]) | |
| def log_variables(func: F) -> F: | |
| @wraps(func) | |
| def wrapper(*args: Any, **kwargs: Any) -> Any: | |
| def tracer(frame, event, arg) -> Optional[Callable]: | |
| if event == "return": | |
| wrapper.locals = frame.f_locals.copy() | |
| return tracer | |
| wrapper.tracer = tracer | |
| sys.settrace(wrapper.tracer) | |
| try: | |
| result: Any = func(*args, **kwargs) | |
| finally: | |
| sys.settrace(None) | |
| for name, value in wrapper.locals.items(): | |
| print(f"{name}: {value}") | |
| return result | |
| wrapper.locals = {} | |
| return wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment