2

What object is being queried when I call dir() in Python's interpreter?

I'm playing with a package that I want to be able to get the names for functions from the global dictionary. I thought that it would be dir(__global) but that wasn't it, nor was dir(sys.modules).

If I type dir() into a fresh interpreter session it says

['__builtins__', '__doc__', '__name__', '__package__'] 

What would be the ob in dir(ob) that would give me this same response?

3
  • that was so much more than I needed to say, but any less and it thought my question was subjective. and as you can see, it is very very much so not. Commented Nov 13, 2011 at 2:05
  • It returns the current local scope if no args are passed to it. Your question could be better worded, as I'm still unsure what it is you are after. Commented Nov 13, 2011 at 2:07
  • how do i address the local scope? it is a python object correct? how do I address this object? Commented Nov 13, 2011 at 2:11

2 Answers 2

2

dir() returns names in the current scope. I can't remember now if it's exactly equivalent to locals().keys(), or are there any differences.

Sign up to request clarification or add additional context in comments.

4 Comments

and how can I address the current scope? what is that object?
@Narcolapser: The local scope is a dictionary behind the scenes, which locals() can return.
thats it! thank you. I'll mark you correct in 5 minutes when it lets me. xD
@eryksun: CPython implementation details are not proof of Python semantics. :P
0

Re-reading your question 8 years later, I now wonder if you are asking about dir() run interactively at the Python prompt, a situation which I and the other answers entirely failed to address.

In that case the actual answer is:

When you type dir() in the Python interpreter, it runs dir() on the __main__ module because that is the namespace in which the Python prompt runs the statements that you type.

To perform this operation yourself, simply run:

import sys dir(sys.modules['__main__']) 

You will see exactly the same names listed as when you run dir() interactively. Try making an assignment like a = 1 then run both plain dir() and also the expression shown above; you will see that they both show the same list of names that now includes 'a'.


The dir() method invokes complex and deep operations to try to predict which attributes might exist on the object you query — but runs under the handicap that it cannot actually try to access the attribute names it finds to see if they would return AttributeError or not. I know, this answer is way more detail than you want right now; but for those who might stumble on this question later with more complicated needs, "Implementing __dir__ (and finding bugs in Pythons)" is a blog post by Michael Food detailing some of the magic.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.