The __dir__()
method is used to get a list of attributes and methods contained by a given object . The method gets called indirectly when we use the builtin dir() function.
The method is especially useful when a user needs to inspect a particular object using the dir() function. It returns the list of valid attributes and methods of an object making it easier to determine the capabilities of the object and decide what operations can be performed on it.
Example with a list:
Example with a custom object:
Overriding the __dir__() Function for custom objects.
All objects have the __dir__ method defined by default. However, classes can override the method to customize the object's available properties and methods. This allows for finer control over which attributes should be exposed and which should remain hidden. It also helps to ensure that only certain attributes are shown in an object's public interface.
class MyClass:
def __dir__(self):
#statements
The method takes no arguments and should return a list containing the attributes and methods available on the object that we want exposed when the builtin dir()
function is called on the object.
A more practical example
Note: Any valid list can be returned by __dir__(), however, it is a good practice to ensure that the method returns a list containing relevant attributes which are actually contained by the object. This can help other developers quickly and easily access information about the object. It also helps to ensure that the code can be understood easily and therefore, easy to maintain.