# 如何在下层函数中找到中层函数中的变量

``````def debug():
"""
Common function used anywhere in Python
It will access all variables where this function called.
all_variables_dictionary
for variable in all_variable_dictionary:
print(f"{variable} = {all_variable_dictionary[variable]}')
"""
print('a10 in globals():',  'a10'  in  globals())
print('a10 in locals():',  'a10'  in  locals())
print(a10)

def f2():
a10 = 5
debug()

f2()``````
``````a10 in globals(): False
a10 in locals(): False
Traceback (most recent call last):
File "<string>", line 178, in run_nodebug
File "D:\module1.py", line 16, in <module>
f2()
File "D:\module1.py", line 14, in f2
debug()
File "D:\module1.py", line 10, in debug
print(a10)
NameError: name 'a10' is not defined``````
Jason Yang

``````import inspect
outer_locals = inspect.currentframe().f_back.f_locals
eval(expression, globals(), outer_locals))``````

``````import inspect

def find_variable():
outer_locals = inspect.currentframe().f_back.f_locals
print(outer_locals)
expression = 'a*b+c'
print(f'{expression} = {eval(expression, globals(), outer_locals)}')

def f():
a = 1
b = 2
c = 3
find_variable()

f()
"""
{'a': 1, 'b': 2, 'c': 3}
a*b+c = 5
"""``````
8个月前 评论
Coolest 8个月前

``````def f2():
a10 = 5
def f1():
nonlocal a10
print(a10)
return f1``````

``````>>> func = f2()
>>> func()
5``````
9个月前 评论
Jason990420 （楼主） 9个月前

``````import inspect
outer_locals = inspect.currentframe().f_back.f_locals
eval(expression, globals(), outer_locals))``````

``````import inspect

def find_variable():
outer_locals = inspect.currentframe().f_back.f_locals
print(outer_locals)
expression = 'a*b+c'
print(f'{expression} = {eval(expression, globals(), outer_locals)}')

def f():
a = 1
b = 2
c = 3
find_variable()

f()
"""
{'a': 1, 'b': 2, 'c': 3}
a*b+c = 5
"""``````
8个月前 评论
Coolest 8个月前