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:
- If the object is a module, the list contains the module’s attribute names.
- If the object is a type or class, the list contains the names of the object’s attributes and its parents (calculated recursively).
- 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__', ...]