/    /  Python – Dir() Function

Python dir() function

The dir() function is a powerful inbuilt function which returns all properties and methods of the specified object without values, even built in properties that are default for all object.



object is parameter which is optional.

dir() returns a valid list of attributes of the object. This function aims to produce the most relevant information rather than the complete information. It behaves differently for different types of objects.

For Class Objects, dir() returns a list of names of all the valid attributes and base attributes. For Modules or Library objects, it returns a list of names of all the attributes of that module. If parameters are not passed it returns a list of names in the current local scope.

If the object has __dir__() method, method is called and it returns the list of attributes. If the object doesn’t have __dir__() method, it tries to find information from __dict__() attribute and from type object. The list returned from dir() may not be complete.

If we import random, then dir() will return the output as the following.

If we create a class Person and define dir() function which will return Name, age and salary of the person. Then, we will create an object Employee of class Person and it is called in print statement. Let us observe the output of this function.

Python Code:

class Person:
     def __dir__ (self):
	return [‘Name’, ‘age’, ‘salary’]
Employee = Person()


[‘Name’, ‘age’, ‘salary’]

dir() function is generally used for debugging in simple programs and even in large projects. This function can list out all attributes of the parameters passed, is useful when handling a lot of functions and classes separately.

It can also list out all available attributes for module or list or dictionary. It provides information on operations we perform with the module, which is very useful when we have very less or no information.