Narcolapser
Narcolapser

Reputation: 6221

Calling dir() in Python

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?

Upvotes: 2

Views: 1201

Answers (2)

Brandon Rhodes
Brandon Rhodes

Reputation: 89405

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.

Upvotes: 0

Cat Plus Plus
Cat Plus Plus

Reputation: 129774

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.

Upvotes: 2

Related Questions