Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 454
Kelketek Avatar asked Mar 23 '12 10:03

Kelketek


3 Answers

Try using Python interpreter stack

like image 187
warvariuc Avatar answered Oct 13 '22 11:10

warvariuc


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.

like image 21
fraxel Avatar answered Oct 13 '22 11:10

fraxel


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>}
like image 42
snoob dogg Avatar answered Oct 13 '22 10:10

snoob dogg