dir()

dir(object)

Returns the attributes of the obj object in alphabetical order. When called without an argument, it returns the names of variables available in the local scope.

  • Defining __dir__ in a class lets you control the result of this function for class instances.
  • This is useful when the class also defines attribute access methods __getattr__ and __getattribute__.
  • For objects whose class does not define __dir__, the function attempts to determine attributes from the __dict__ data.
  • The returned list may not include all attributes, especially with overridden __getattr__.

The mechanism for extracting names varies for different types:

  1. If the object is a module, the list contains the module’s attribute names.
  2. If the object is a type or class, the list contains the names of the object’s attributes and its parents (calculated recursively).
  3. In other cases, the list contains the names of the object’s attributes, its class, and parent classes (calculated recursively).

Parameters

The dir() function takes one parameter:

  • object: can be an empty/filled tuple, list, set, dictionary, etc., or any user-defined object.

Return Value

  • The dir() function returns a list of valid attributes of the passed object.

Examples

dir(int)  # ['__abs__', '__add__', '__and__', '__bool__', ...]
dir('some')  # ['__add__', '__class__', '__contains__', '__delattr__', ...]