Created
September 27, 2022 17:03
-
-
Save psobot/9a96076d597591c0ee4cd79d3cdfa82e to your computer and use it in GitHub Desktop.
Search a Python stack for a variable with a given name
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 typing import Tuple, Any | |
def search_stack_for_variable(variable_name: str, frame=None) -> Tuple[str, Any]: | |
if frame is None: | |
frame = inspect.currentframe() | |
if variable_name not in frame.f_locals: | |
if frame.f_back is None: | |
raise ValueError(f"No variable named \"{variable_name}\" found in callstack.") | |
return search_stack_for_variable(variable_name, frame.f_back) | |
else: | |
try: | |
value = frame.f_locals.get(variable_name) | |
_, _, function_name, _, _ = inspect.getframeinfo(frame) | |
return function_name, value | |
finally: | |
del frame |
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 pytest | |
from stacksearch import search_stack_for_variable | |
def test_two_levels(): | |
def fun_one(): | |
my_variable = 123 | |
fun_two() | |
def fun_two(): | |
my_other_variable = 234 | |
leaf_function() | |
def leaf_function(): | |
assert search_stack_for_variable("my_variable") == ("fun_one", 123) | |
assert search_stack_for_variable("my_other_variable") == ("fun_two", 234) | |
with pytest.raises(ValueError): | |
search_stack_for_variable("some_nonexistent_variable") | |
fun_one() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment