1

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!

0

2 Answers 2

4

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)
   ...: 
Sign up to request clarification or add additional context in comments.

Comments

4

vaultah's answer is best, I think, but you could also use eval to get the values:

for item in dir():
    print('{} : {}'.format(item, eval(item)))

There is usually a lot of stigma regarding the use of eval (it's dangerous!) and I will probably be downvoted for this answer, however, I think that it OK in this limited case.

1 Comment

I will probably be downvoted for this answer ... Why? You've just provided an alternative ... :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.