Created
July 15, 2024 19:13
-
-
Save CodeByAidan/3c35d0e5d8446bb36a7616247a6cece0 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