我知道这是通常不应该做的事情,我知道它的原因。但是,我在一个类中创建一个调试函数,该函数应显示有关调用它的模块的一些信息。
我需要知道如何在名称空间中找到一个变量,该变量应该始终存在于既调用此模块又需要此函数的程序中。
我知道可以通过以下方式获得主要名称空间:
import __main__
但我猜这包括从第一个启动模块开始的所有内容,我只想要一个调用此模块的那个。
答案 0 :(得分:2)
答案 1 :(得分:1)
调用'调试对象'的对象应该只传递self
作为参数。然后'调试对象'将有权访问所有调用者属性。例如:
class Custom(object):
def __init__(self):
self.detail = 77
def call_bug(self, name):
name.bug(self)
class Debugger(object):
def bug(self, caller):
print caller.__dict__
custom = Custom()
debugger = Debugger()
custom.call_bug(debugger)
output:
{'detail': 77}
这个原则适用于不同的文件。
答案 2 :(得分:1)
warvariuc已经回答了,但是一个例子也可能很棒。如果要了解以前的名称空间,可以使用inspect
:
import inspect
from pprint import pprint
def foo():
frame = inspect.currentframe()
previous_namespace = frame.f_back.f_locals
pprint(previous_namespace)
def bar():
def inner_function():
pass
a = "foo"
b = 5
c = {}
d = []
foo()
然后您可以做:
>>> bar()
{'a': 'foo',
'b': 5,
'c': {},
'd': [],
'inner_function': <function bar.<locals>.inner_function at 0x0000000002D6D378>}