nvcleemp
nvcleemp

Reputation: 560

Access parent namespace in python

def c():
    def a():
        print dir()

    def b():
        pass

    a()

c()

Probably a really simple question, but I can't seem to find an answer by googling. I have the code above, and I want the a method to print the namespace containing the methods a and b, i.e. I want it to print the namespace of the point form which it is called. Is this possible? Preferably in Python 2.x

Upvotes: 5

Views: 2702

Answers (2)

reclosedev
reclosedev

Reputation: 9502

You can use inspect module from standard Python library:

import inspect

def c():
    def a():
        frame = inspect.currentframe()
        print frame.f_back.f_locals

    def b():
        pass

    a()

c()

But frames should be deleted after use, see note.


Answer to comment.

Possible way to restrict inspect features for students:

import sys
sys.modules['inspect'] = None
sys._getframe = None

Upvotes: 6

Ski
Ski

Reputation: 14487

I would go with locals() like this:

def c():
    def a(locals_):
        print locals_

    def b():
        pass

    a( locals() )

c()

Upvotes: 2

Related Questions