9) d. dir Function

Have you ever used the dir command in a Windows terminal (command-prompt)? If you did, you would notice that it helpfully lists out all the directories and files present in your active folder. Python’s dir is somewhat similar.

dir is one of the built-in Python functions whose purpose is to list attributes and methods of an object/module that is passed to it as an argument.

Try to run the following code and notice its output:

1
2
Output:
['__add__', '__contains__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__repr__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isnumeric', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'upper', 'zfill']



Whenever you use dir(<module_name> / <object_name>), python will list out all the attributes and methods for that module or object.

Here is an example where you create a list object and use the dir function on it.

1
2
Output:
['__add__', '__contains__', '__delitem__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__repr__', '__rmul__', '__setattr__', '__setitem__', '__str__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']



It can be useful when using the Python console interactively to list objects’ attributes if you are not familiar with their API. Some libraries even create their attributes on the fly and it is not always obvious which attributes are available. The dir() function can help you refer to the methods/attributes that are available in the given context.