Python dir() Method – [With Example]

In this tutorial we will learn about the python dir() method and its uses.

Python dir() Method

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

The syntax of dir() is:


Python dir() Method Parameters

dir() takes only a single parameter.

object – the dir() function attempts to return all attributes of a specific object. It is optional.

Let check some example on the usage of dir() function.

Example 1: How dir() works?

number = [5,6,7]

Output will be as follow:

[‘__add__’, ‘__class__’, ‘__contains__’, ‘__delattr__’, ‘__delitem__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__getitem__’, ‘__gt__’, ‘__hash__’, ‘__iadd__’, ‘__imul__’, ‘__init__’, ‘__init_subclass__’, ‘__iter__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__mul__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__reversed__’, ‘__rmul__’, ‘__setattr__’, ‘__setitem__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘append’, ‘clear’, ‘copy’, ‘count’, ‘extend’, ‘index’, ‘insert’, ‘pop’, ‘remove’, ‘reverse’, ‘sort’]

Example 2: How to use dir() on User-defined Objects.

class Dog:
def __dir__(self):
dogType = Dog()

The output will be as follows.

[‘age’, ‘bread’, ‘color’]

Rules of dir() function

dir() function tries to return a list of valid attributes of the object.

If the object has __dir__() method, the method will be called and must return the list of attributes.

If the object doesn’t have __dir__() method, this method tries to find information from the __dict__ attribute (if defined) and type object. In this case, the list returned from dir() may not be complete.

If an object is not passed to the dir() method, it returns the list of names in the current local scope.