What is the output of dir () Python?

It's just a list, so you can loop over it too:

for entry in dir(obj): print repr(entry)

or you could use pprint.pprint() to have the list formatted 'prettily' for you.

Demo on the pprint module itself:

>>> import pprint >>> pprint.pprint(dir(pprint)) ['PrettyPrinter', '_StringIO', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_commajoin', '_id', '_len', '_perfcheck', '_recursion', '_safe_repr', '_sorted', '_sys', '_type', 'isreadable', 'isrecursive', 'pformat', 'pprint', 'saferepr', 'warnings']

Today we are going to discuss the Python dir() method.

So let’s get started.

The Python dir() Method Basics

The dir() method in Python is widely used to get the list of names of the attributes of the passed object in an alphabetically sorted manner.

Here, object is an optional argument. When any Python object is passed to the dir() method, it returns a list containing all the attributes of that object. And when nothing is passed, the method returns back the list of all the local attributes.

For objects with defined __dir__() method, the dict() leads to the call for it and hence should return a list of attributes related to the object.

Python dir() Example

Now that we have a basic idea of the dir() method, let us take a look at an example to have a better understanding.

#empty dir() print("dir() :", dir()) #list initialisation list1 = ['name', 'class', 'roll'] #dictionary initialisation dict1 = {0: 'bad', 5: 'fair', 10: 'good'} print("\ndir(list1) :", dir(list1)) print("\ndir(dict1) :", dir(dict1))

Output:

dir() : ['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__'] dir(list1) : ['__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'] dir(dict1) : ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']

As you can see, here we have at first passed nothing, then a list object, and finally a dictionary object to the dir() method and have printed out the returned list.

From the above output, we can clearly see the different attributes available for the list and dictionary objects. For the case where nothing is passed to the function, we get all the names of the methods or attributes in the local scope.

Working with the dir() Method in Python

So now let us try out some more examples where we try to use the dir() function on objects of user-defined classes as well as ones with defined __dir__() method.

1. With Custom Objects

Now that we have applied the dir() method for built-in classes like lists and dictionaries. Let us try finding out the results for custom objects of a user-defined class with undefined __dir__().

#class class shape: name = "rectangle" sides = 4 obj = shape() print(dir(obj)) #dir for our custom object

Output:

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name', 'sides']

Here, obj is an object of the shape class with name rectangle and sides = 4. Passing this obj object to the dir() method, we get the above set of attributes.

Note, this list includes the name as well as the sides variable too.

2. With defined __dir__()

As mentioned earlier in this article, for objects with defined __dir__() method, the dir() method calls the corresponding __dir__() method which must again return a list of attributes.

Let us try to understand that with an example.

#class class shape: name = "rectangle" sides = 4 def __dir__(self): return ['Square','Circle'] obj = shape() print(dir(obj)) #dir for our custom object

Output:

What is the output of dir () Python?
Python dir() method output

As you can see, for the object obj of the shape class, the __dir__() method is called and the above list of attributes is returned at the site of dir(obj) call.

Conclusion

So in this tutorial, we learned about the Python dir() method, how it works as well as how we can use it in different cases.

For any further questions related to this topic, feel free to comment below.

References

The dir() function of Python is used to retrieve the attributes and methods of any object like string, list, dictionary, function, class, module, etc. This function returns the list of attributes and methods of the standard library that is available after initializing the Python program. The purposes of using the dir() function and the different uses of the dir() function in Python have been shown in this tutorial.

Syntax:

The dir() function can be used with the argument and without the argument. It returns different types of attributes and methods based on the object used as the argument. The syntax of this function is given below.

dir([object])

  • If no argument is passed in this function, then the list of the names of the current local scope will be returned by this function.
  • If the class object is used as the argument, then the dir() function will return the list of all valid attributes.
  • If the module is used as the argument, then the dir() function will return the list of all attributes contained by that module.

Example-1: Use of dir() function without argument

Create a python file with the following script to check the returned value of the dir() function when it is used without any argument. In the script, the dir() function without argument is called before importing any module and after importing two modules.

#Print the output of dir() function before importing any module
print("The output of dir() function before import:\n", dir())

#Import modules


import sys
import os

#Print the output of dir() function after importing sys and os modules


print("\nThe output of dir() function after import:\n", dir())

Output:
The following output will appear after executing the above script. After importing the modules, the output shows that os and sys have been added to the dir() output.

What is the output of dir () Python?

Example-2: Use of dir() function for the string as an argument

Create a python file with the following script where the string object has been used as the argument of the dir() function. In this case, the dir() function will return the list of all attributes of the string object.

#Define a string value
text = 'LinuxHint'
#Print the output of dir() function for string value
print("\nThe output of dir() function for the string data:\n", dir(text))

Output:
The following output will appear after executing the above script.

What is the output of dir () Python?

Example-3: Use of dir() function for the list as the argument

Create a python file with the following script where the list object has been used as the argument of the dir() function. In this case, the dir() function will return the list of all attributes of the list object.

#Define a list of decimal numbers
numList = [6.7, 3.2, 8.0, 2.8, 9.1, 1.5, 0.9]
#Print the output of dir() function for the list
print("\nThe output of dir() function for the list of numbers:\n", dir(numList))

Output:
The following output will appear after executing the above script.

What is the output of dir () Python?

Example-4: Use of dir() function for the tuple as argument

Create a python file with the following script where the tuple object has been used as the argument of the dir() function. In this case, the dir() function will return the list of all attributes of the tuple object.

#Define a tuple of string
strTuple = ['Book', 'Pen', 'Pencil','Eraser','Ruler','Color Pencil']
#Print the output of dir() function for the tuple
print("\nThe output of dir() function for the tuple:\n", dir(strTuple))

Output:
The following output will appear after executing the above script.

What is the output of dir () Python?

Example-5: Use of dir() function for the dictionary as argument

Create a python file with the following script where the dictionary object has been used as the argument of the dir() function. In this case, the dir() function will return the list of all attributes of the dictionary object.

#Define a dictionary
dicData = {'8967':90, '4523':85, '9123':75,'6580':88}
#Print the output of dir() function for the dictionary
print("\nThe output of dir() function for the dictionary:\n", dir(dicData))

Output:
The following output will appear after executing the above script.

What is the output of dir () Python?

Example-6: Use of dir() function for the object of a class

Create a python file with the following script where the user-defined class object has been used as the argument of the dir() function. In this case, the dir() function will return the list of all attributes of the class object.

#Define a class with a constructor
class Client:

   def __init__(self, name, mobile, email):


      self.name = name
      self.mobile = mobile
      self.email = email

#Create an object of the class


objClient = Client('Amir Hossain','+8801937865645','[email protected]' )

#Print the dir() function output for the object


print("The output of the dir() function for the object:\n", dir(objClient))

Output:
The following output will appear after executing the above script.

What is the output of dir () Python?

Example-7: Use of dir() function for a particular module

Create a python file with the following script where the module has been used as the argument of the dir() function. The dir() function has been used with sys and randint modules in the script. The dir() function will return the list of all attributes of these modules as the output.

#Import sys module
import sys
#Import randint from random
from random import randint

#Print the output of dir() function for the sys


print("The output of the dir() for sys:\n",dir(sys))
#Print the output of dir() function for the randint
print("\nThe output of the dir() for randint:\n",dir(randint))

Output:
The following output will appear after executing the above script. The first output shows the attributes of the sys module, and the second output shows the attributes of the randint module.

What is the output of dir () Python?

Conclusion:

The uses of the dir() function without any argument and with the different arguments have been shown in this tutorial using multiple examples. I hope using the dir() function in python will be cleared after reading this tutorial.