Search code examples
pythondir

how to use loop to get values in dir()?


Why i can't get the values in the items in dir() with loop:

for item in dir():
    print(item)

It just print

 __builtins__
 __doc__
 __loader__
 __name__
 __package__
 __spec__

So, how can i use loop to print the value in item, i.e "__main__" in __name__ Thanks!


Solution

  • Calling dir without the argument is logically equivalent to list(locals()), as in getting the list of names of variables in the current namespace (keys of locals() dictionary).

    You'd use the items method of locals() instead:

    In [5]: for name, value in list(locals().items()):
       ...:     print(name, value)
       ...: