简体   繁体   中英

Access namespace of calling module

I know this is something one normally should not do, and I know the reasons for it. However, I am making a debugging function within a class that should display some information about the module that called it.

I need to know how to go up one level in the name space to find a variable that should always exist in a program that both calls this module and needs this function.

I know one can get the main name space with:

    import __main__

But I'm guessing that this includes everything from the very first launched module onward, and I just want the one that called this one.

尝试使用Python解释器堆栈

warvariuc already answered but an example could be great too. If you want to be aware of the previous namespace, you can use 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()

Then you can do:

>>> bar()

{'a': 'foo',
 'b': 5,
 'c': {},
 'd': [],
 'inner_function': <function bar.<locals>.inner_function at 0x0000000002D6D378>}

The object that calls the 'debugging object' should just pass self as a parameter. Then the 'debugging object' will have access to all the callers attributes. For example:

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}

This principle will work fine across different files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM