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

如题, 不能使用参数传递, 不能使用 global !

请问在执行被呼叫函数 debug 中, 呼叫函数中当时, 除了 global 的变量以外, local 的变量如何取得 ?

目的: 某些情况不适合把所有的变量宣告, 比如 debug 函数, 当f2 呼叫debug 时, debug 要处理在f2 能看到的所有的变量, 它可能是是local, 也可能是global. 使用global或nonlocal 宣称所有的变量, 或者把debug 只定义在f2 都是不合适的, 因为目的中, debug 是个通用函数, 不只使用在f2.

目的不是只针对 debug.

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
Jason990420
最佳答案

过了十二天, 没有答案, 我自己来吧 !

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

范例: eval 会先找 outer_locals, 再找 globals()

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
"""
3年前 评论
Coolest 3年前
讨论数量: 2

不是很清楚楼主像这样做的目的,但可以尝试下 Python 中的闭包机制:

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

执行结果:

>>> func = f2()
>>> func()
5
3年前 评论
Jason990420 (楼主) 3年前
Jason990420

过了十二天, 没有答案, 我自己来吧 !

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

范例: eval 会先找 outer_locals, 再找 globals()

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
"""
3年前 评论
Coolest 3年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!