Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access parent namespace in python

Tags:

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

like image 626
nvcleemp Avatar asked Feb 03 '12 14:02

nvcleemp


People also ask

How do I find the namespace in Python?

Use vars() to convert your namespace to a dictionary, then use dict. get('your key') which will return your object if it exists, or a None when it doesn't.

What is use of namespace in Python?

Namespace is a way to implement scope. In Python, each package, module, class, function and method function owns a "namespace" in which variable names are resolved. When a function, module or package is evaluated (that is, starts execution), a namespace is created. Think of it as an "evaluation context".

What is built-in namespace in Python?

A namespace containing all the built-in names is created when we start the Python interpreter and exists as long as the interpreter runs. This is the reason that built-in functions like id() , print() etc. are always available to us from any part of the program. Each module creates its own global namespace.

How are namespaces and variable scopes different from each other?

Namespaces are collections of different objects that are associated with unique names whose lifespan depends on the scope of a variable. The scope is a region from where we can access a particular object. There are three levels of scopes: built-in (outermost), global, and local.


1 Answers

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
like image 141
reclosedev Avatar answered Sep 27 '22 00:09

reclosedev