In this lesson, you’ll learn about the built-in function dir()
. It returns a list of defined names in a namespace. Without arguments, it produces an alphabetically sorted list of names in the current local symbol table:
>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__',
'__spec__', 'help']
>>> spam = [1, 2, 3, 4, 5]
>>> spam
[1, 2, 3, 4, 5]
>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__',
'__spec__', 'help', 'spam']
>>> class Extraclassy():
... pass
...
>>> x = Extraclassy()
>>> dir()
['Extraclassy', '__builtins__', '__doc__', '__loader__', '__name__',
'__package__', '__spec__', 'help', 'spam', 'x']
Note how the first call to dir()
above gives several names that are automatically defined and already in the namespace when the interpreter starts. As new names are defined (spam
, Extraclassy
, x
), they appear on subsequent invocations of dir()
.
This can be useful for identifying what exactly has been added to the namespace by an import statement:
>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__',
'__spec__', 'help']
>>> import mod
>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__',
'__spec__', 'help', 'mod']
>>> mod.s
'Computers are useless. They can only give you answers.'
>>> mod.printy([1, 2, 3])
arg = [1, 2, 3]
>>> from mod import a, Classy
>>> dir()
['Classy', '__builtins__', '__doc__', '__loader__', '__name__', '__package__',
'__spec__', 'a', 'help', 'mod']
>>> a
[100, 200, 300]
>>> y = Classy()
>>> y
<mod.Classy object at 0x1034a5978>
>>> from mod import s as string
>>> dir()
['Classy', '__builtins__', '__doc__', '__loader__', '__name__', '__package__',
'__spec__', 'a', 'help', 'mod', 'string', 'y']
>>> s
Traceback (most recent call last):
File "<input>", line 1, in <module>
s
NameError: name 's' is not defined
>>> string
'Computers are useless. They can only give you answers.'
When given an argument that is the name of a module, dir()
gives the names defined in the module:
>>> import mod
>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__',
'__spec__', 'help', 'mod']
>>> dir(mod)
['Classy', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__',
'__name__', '__package__', '__spec__', 'a', 'printy', 's']
>>> dir()
['__builtins__', '__doc__', '__loader__', '__name__', '__package__',
'__spec__', 'help', 'mod']
>>> from mod import *
>>> dir()
['Classy', '__builtins__', '__doc__', '__loader__', '__name__', '__package__',
'__spec__', 'a', 'help', 'mod', 'printy', 's']
keyurratanghayra on April 14, 2020
Could not be easier than this. Awsome job here, Chris!