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
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.
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".
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With