Next / Previous / Contents / TCC Help System / NM Tech homepage

21.5. dir(): Display a namespace's names

The purpose of the dir() function is to find out what names are defined in a given namespace, and return a list of those names. If called without arguments, it returns a list of the names defined in the local namespace. This function can be very handy for finding out what items are in a module or class.

Certain special names are found in most or all namespaces:

In this example sequence, we'll show you what is in the global namespace just after starting up Python. Then we'll import the math module and display its names.

>>> dir()
['__builtins__', '__doc__', '__name__']
>>> x=5; forkTail='Tyrannus'
>>> dir()
['__builtins__', '__doc__', '__name__', 'forkTail', 'x']
>>> print __doc__
>>> print __name__
>>> import math
>>> print math.__name__
>>> dir(math)
['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil'
, 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', '
hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'si
nh', 'sqrt', 'tan', 'tanh']
>>> print math.__doc__
This module is always available.  It provides access to the
mathematical functions defined by the C standard.
>>> print math.log10.__doc__
log10(x) -> the base 10 logarithm of x.
>>> print __builtins__
<module '__builtin__' (built-in)>
>>> for k, name in enumerate(dir(__builtins__)):
...     if (k%4)==3: print
...     print name,
ArithmeticError AssertionError AttributeError
BaseException BufferError BytesWarning DeprecationWarning
EOFError Ellipsis EnvironmentError Exception
False FloatingPointError FutureWarning GeneratorExit
IOError ImportError ImportWarning IndentationError
IndexError KeyError KeyboardInterrupt LookupError
MemoryError NameError None NotImplemented
NotImplementedError OSError OverflowError PendingDeprecationWarning
ReferenceError RuntimeError RuntimeWarning StandardError
StopIteration SyntaxError SyntaxWarning SystemError
SystemExit TabError True TypeError
UnboundLocalError UnicodeDecodeError UnicodeEncodeError UnicodeError
UnicodeTranslateError UnicodeWarning UserWarning ValueError
Warning ZeroDivisionError _ __debug__
__doc__ __import__ __name__ __package__
abs all any apply
basestring bin bool buffer
bytearray bytes callable chr
classmethod cmp coerce compile
complex copyright credits delattr
dict dir divmod enumerate
eval execfile exit file
filter float format frozenset
getattr globals hasattr hash
help hex id input
int intern isinstance issubclass
iter len license list
locals long map max
min next object oct
open ord pow print
property quit range raw_input
reduce reload repr reversed
round set setattr slice
sorted staticmethod str sum
super tuple type unichr
unicode vars xrange zip