![](/img/trans.png)
[英]How to access to calling module namespace from called module in Python?
[英]Access namespace of calling module
我知道這是通常不應該做的事情,我知道它的原因。 但是,我在一個類中創建一個調試函數,該函數應顯示有關調用它的模塊的一些信息。
我需要知道如何在名稱空間中找到一個變量,該變量應該始終存在於既調用此模塊又需要此函數的程序中。
我知道可以通過以下方式獲得主要名稱空間:
import __main__
但我猜這包括從第一個啟動模塊開始的所有內容,我只想要一個調用此模塊的模塊。
嘗試使用Python解釋器堆棧
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>}
調用'調試對象'的對象應該只將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}
這個原則適用於不同的文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.