It's just a list, so you can loop over it too: Show
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 BasicsThe 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() ExampleNow 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 PythonSo 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 ObjectsNow 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: Python dir() method outputAs 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. ConclusionSo 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])
Example-1: Use of dir() function without argumentCreate 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 #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: Example-2: Use of dir() function for the string as an argumentCreate 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 Output: Example-3: Use of dir() function for the list as the argumentCreate 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 Output: Example-4: Use of dir() function for the tuple as argumentCreate 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 Output: Example-5: Use of dir() function for the dictionary as argumentCreate 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 Output: Example-6: Use of dir() function for the object of a classCreate 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 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: Example-7: Use of dir() function for a particular moduleCreate 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 #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: 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. |