Max
Max

Reputation: 8045

how to get the current scope in python

is there any reference to point to the current scope , i look up many articles and couldn't find the answer ,for example i want to print every var's content in current scope

for x in list(locals()):
    print(x)

but only give me this,the var's name

__builtins__
__file__
__package__
__cached__
__name__
__doc__

i dont want code like this

print(__builtins__)
print(__file__)
print(__package__)
print(__cached__)
print(__name__)
print(__doc__)
....

Upvotes: 5

Views: 15061

Answers (4)

Rob Cowie
Rob Cowie

Reputation: 22619

Massive overkill... Wrap the filtering and printing of local namespace in a function.

I don't recommend this. I'm posting it predominantly to show it can be done and to get comments.

import inspect

def print_local_namespace():
    ns = inspect.stack()[1][0].f_locals
    for k, v in ns.iteritems():
        if not k.startswith('__'):
            print '{0} : {1}'.format(k, v)


def test(a, b):
    c = 'Freely'
    print_local_namespace()
    return a + b + c


test('I', 'P')

Upvotes: 5

Bakuriu
Bakuriu

Reputation: 101969

What do you mean by "current scope"? If you mean only the local variables, then locals() is the correct answer. If you mean all the identifiers that you can use[locals + globals + nonlocals] than things get messier. Probably the simpler solution is this one.

If you don't want the __.*__ variables, just filter them out.

Upvotes: 2

Simon Bergot
Simon Bergot

Reputation: 10582

To also get the values, you can use:

for symbol, value in locals().items():
    print symbol, value

locals() gives you a dict. Iterating over a dict gives you its keys. To get the list of (key, value) pairs, use the items method.

Upvotes: 6

Andy Hayden
Andy Hayden

Reputation: 375555

To print only those variable names in locals() which do not start with '__':

for local_var in list(locals()):
    if not local_var.startswith('__'): print local_var

Upvotes: 2

Related Questions