liveBook · Manning

Dir()

As explained in The Quick Python Book, Fourth Edition

dir() is Python's built-in function for listing names and attributes available in a namespace or associated with an object, module, or type.

dir() lists names and attributes available in a namespace or associated with an object, module, or type. Use it as a quick inventory when exploring unfamiliar code, checking members, or debugging. section 2.4

Use the argument form that matches what you want to inspect:

  • Call dir() without arguments to list names in the current interactive namespace. section 2.4
  • Call dir(module) to list names defined by a module, or dir(type) to inspect methods and other members associated with a type. section 2.4 section 10.7.1
  • Treat the result as a name list rather than a display of current values or namespace settings; use help() for targeted documentation. section 2.4 section 10.7.1

Inspecting a namespace and a type

dir() # names currently available, including variables and interactive helpers dir(int) # integer methods and attributes, including __add__, __bool__, and __doc__ section 2.4

Finding a mistyped name

x1 = 6 xl = x1 - 2 dir() # reveals both x1 and xl, making the lowercase l visible section 10.7.1

dir()
 
['In',
 'Out',
 '_',
 '__',
 '___',
 '__builtin__',
 '__builtins__',
 '__doc__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 '_dh',
 '_i',
 '_i1',
 '_i2',
 '_ih',
 '_ii',
 '_iii',
 '_oh',
 'exit',
 'get_ipython',
 'quit',
 'x']
 
dir(int)
 
['__abs__',
 '__add__',
 '__and__',
 '__bool__',
 '__ceil__',
 '__class__',
 '__delattr__',
 '__dir__',
 '__divmod__',
 '__doc__',
 '__eq__',
 '__float__',
 '__floor__',
 '__floordiv__',
 '__format__',
 '__ge__',
 '__getattribute__',
 ... (continues with more items... ]

Compare the inventories returned by dir() and dir(int), including interactive names and integer members. section 2.4

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines argument forms and practical uses, but stops short of explaining attribute lookup or implementation details.
Examples
Demonstrates dir(), dir(int), built-in names, and detecting a mistyped variable in an interactive namespace.
What it assumes
Assumes familiarity with Python names and objects while illustrating namespaces and built-ins through inspection.
What you can do after
Diagnose missing or unexpected names and explore available members before consulting targeted help().
How it connects
Connects namespaces, modules, types, attributes, debugging, and help().

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.