3

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__)
....
Max
  • 7,667
  • 9
  • 31
  • 38
  • The underscore variables ARE part of your current scope. If you don't want them, just skip them. – gecco Aug 31 '12 at 09:05
  • @gecco he wants to print the values of the variables, not to skip them. The for loop in his post prints the name of the variables, not there vaues – miracle173 May 27 '17 at 10:47

4 Answers4

4

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.

Simon Bergot
  • 9,930
  • 7
  • 37
  • 54
  • if u run your code,will show you these,RuntimeError: dictionary changed size during iteration – Max Aug 31 '12 at 09:20
  • what version of python are you using? Ihave changed the code to something working with 2.7 – Simon Bergot Aug 31 '12 at 09:29
  • 1
    This fails in Python 3.6 with the same RuntimeError. – miguelmorin Dec 10 '18 at 15:12
  • to avoid the RuntimeError: dictionary changed size during iteration, use this code: d = { k : v for k,v in locals().items() if v} to copy the dictionary and then print the symbol and value like above. – aksinghdce Mar 24 '19 at 19:43
4

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')
Rob Cowie
  • 21,692
  • 6
  • 61
  • 56
  • 1
    This is iterating over call stack frames, not definition scopes. You want to got to parent scopes, not parent stack frames. – Mitar Apr 30 '18 at 18:57
2

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
Andy Hayden
  • 328,850
  • 93
  • 598
  • 514
2

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.

Community
  • 1
  • 1
Bakuriu
  • 92,520
  • 20
  • 182
  • 218