Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Built-in Functions

Python dir() function

Reference for Python dir(): list the names in the current scope or the attributes of an object, how __dir__ customizes it, and what the result leaves out.

dir() returns a sorted list of names. With no argument it lists the names defined in the current local scope. With an object it lists the names of that object's attributes: instance data, methods inherited from its class and base classes, and for modules, everything the module defines.

It is mainly an exploration tool. In a console or notebook you use it to answer "what can I do with this object?". It is not a precise reflection API: the result is a best-effort list meant for humans, and a class can customize it.

Python
print(dir("text")[:3])
# ['__add__', '__class__', '__contains__']

Try it

Python Names in a scope and on an object

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Customizing dir() with __dir__

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
dir()
dir(object)
Name Description
object Optional. Any object: an instance, a class, a module, a function. Omit it to list the current local scope.

Return value: a new list of strings, sorted alphabetically.

Raises: TypeError if the object's __dir__() does not return an iterable of names.

Usage notes

  • Without an argument dir() behaves like sorted(locals()): at module level it lists global names, inside a function the local variables. Use locals() or globals() when you need the values too.
  • With an object it calls the object's __dir__() method and sorts the result. The default implementation gathers the instance __dict__ plus the attributes of the class and its bases.
  • Classes list their own attributes and those of their bases, but not the metaclass attributes.
  • Dynamic attributes can be missing. Names produced by __getattr__ do not appear unless you add them in __dir__(), as the second example does.
  • Dunder names are included. Filter with not name.startswith("_") to see the public API.
  • Not a security or contract tool. A name in dir() does not guarantee that reading it works, and a missing name does not guarantee that it is absent. Use hasattr() or getattr() to test a specific name.
  • Mutation: dir() returns a fresh list each time; changing it does not affect the object.
  • Sorting is by string, so uppercase names come before lowercase ones.