Lesson 5: Python dir()

dir() is a fantastic function that will show you all the methods you might want to know about an object.

For instance, you can simply type dir(str) and you will get all the properties and methods of string type in Python.

You might also have a string variable, let’s say called: a.

You can also just type dir(a) and since this variable is a string type you will get all the properties and methods of string type listed for you.

Function 1: dir()

dir() function will show you the methods and properties (attributes) of an object.

Used Where?

  • Listing methods of any object.
  • After creating a class to check its attributes.

Syntax do(s)

1) simply type dir() and put your object inside the parenthesis

Syntax don't(s)

1) na

Example 1

>>> lst = [1,2,3,4,5]
>>> dir(lst)

[‘__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’]

You don’t have to use dir function inside a print() function for it to print the output on the display.

You can see a list of handy list methods are listed after running dir() on a list type variable. dir() can also be run with class name directly such as: dir(list)

‘append’, ‘clear’, ‘copy’, ‘count’, ‘extend’, ‘index’, ‘insert’, ‘pop’, ‘remove’, ‘reverse’, ‘sort’

We have previously seen range() function which creates a convenient range type object. Let’s discover what attributes this type might have.

Example 2

>>> rng = range(3)
>>> print(rng)

[‘__bool__’, ‘__class__’, ‘__contains__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__getitem__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__iter__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__reversed__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘count’, ‘index’, ‘start’, ‘step’, ‘stop’]

Output shows special names with double underscores, count and index methods and start, step and stop data descriptors that are used in range function.

Example 3

dir() can also be run on functions directly.

>>> print(input)

[‘__call__’, ‘__class__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__le__’, ‘__lt__’, ‘__module__’, ‘__name__’, ‘__ne__’, ‘__new__’, ‘__qualname__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__self__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘__text_signature__’]

As you can see input function will return lots of special attributes regarding its class.

Tips

1- dir() is not only a fantastic tool to refresh your memory but also it is one of the steps to the coding independence.

2- Through tools like dir() you will start to gradually build confidence and start handling exploration of an object self-sufficiently.

3- Gaining confidence and independence are crucial steps in programming proficiency and it will become more and more common in your coding routine.

Let’s see an example

Example 4

Let’s see the methods of dict object.

>>> print(dir(dict))

[‘__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’]

If you look at the more regular looking names (without double underscores), you can recognize some of the commonly used dictionary methods such as clear, copy, get, items and keys among other methods. 

Advanced Concepts (Optional)

1- When you run the dir() function on an object you might see names with leading and trailing double underscores. These are special (also called magic) variables and methods regarding an object class. They are sort of under the hood attributes and you don’t have to worry about them at this point.

Let’s see an example.

Example 5

Below example will give everything until last 2 elements

>>> print(dir(str))

[‘__add__’, ‘__class__’, ‘__contains__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__getitem__’, ‘__getnewargs__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__iter__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__mod__’, ‘__mul__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__rmod__’, ‘__rmul__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘capitalize’, ‘casefold’, ‘center’, ‘count’, ‘encode’, ‘endswith’, ‘expandtabs’, ‘find’, ‘format’, ‘format_map’, ‘index’, ‘isalnum’, ‘isalpha’, ‘isascii’, ‘isdecimal’, ‘isdigit’, ‘isidentifier’, ‘islower’, ‘isnumeric’, ‘isprintable’, ‘isspace’, ‘istitle’, ‘isupper’, ‘join’, ‘ljust’, ‘lower’, ‘lstrip’, ‘maketrans’, ‘partition’, ‘replace’, ‘rfind’, ‘rindex’, ‘rjust’, ‘rpartition’, ‘rsplit’, ‘rstrip’, ‘split’, ‘splitlines’, ‘startswith’, ‘strip’, ‘swapcase’, ‘title’, ‘translate’, ‘upper’, ‘zfill’]

As you can see there are some names with double underscores and then you can see the more regular looking names some of which should be familiar from previous lessons such as: lower, upper, strip, split, join etc.

Lesson 6

Nested Data