Python dir() function With Examples

Python dir() function attempts to return a list of valid attributes for the given object. If no argument provided, then it returns the list of names in the current local scope.

Python dir()

Python dir() function syntax is:


dir([object])

If the object contains __dir__() function, then this function will be called. This function must return the list of attributes.

The list of attribute names is sorted in alphabetical order.

Let’s look at some examples of dir() function.

dir() with no argument


print('ndir() with no argumentn')
print(dir())

Output:


dir() with no argument
['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__']

Note that the output depends on the program and python installation, so don’t worry if it’s different in your system.

dir() with tuple and list


print('ndir() with tuple argumentn')
t = (1, 2)
print(dir(t))
print('ndir() with list argumentn')
l = [1, 2]
print(dir(l))

Output:


dir() with tuple argument
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'count', 'index']
dir() with list argument
['__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']

Note that the elements in the list are sorted alphabetically.

dir() with custom object


class Data:
    id = 0
    name=""
print('ndir() with custom object argumentn')
d = Data()
print(dir(d))

Output:


dir() with custom object argument
['__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__', 'id', 'name']

dir() with module object

Let’s see the output of dir() function with a module object, I am using namedtuple from collections module.


from collections import namedtuple
n = namedtuple('Vowels', 'a,e,i,o,u')
print('ndir() with module object argumentn')
print(dir(n))

Output:


dir() with module object argument
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__module__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '_asdict', '_fields', '_fields_defaults', '_make', '_replace', 'a', 'count', 'e', 'i', 'index', 'o', 'u']

Note that the module’s attributes are also returned by dir() function.

dir() with __dir__() function

Let’s define a class with __dir__() function and see if it’s called by dir() function or not.


class Color:
    def __dir__(self):
        print('__dir__() function called')
        return ['Red', 'Green', 'Blue']
print('ndir() with __dir__ method defined in objectn')
c = Color()
print(dir(c))

Output:


dir() with __dir__ method defined in object
__dir__() function called
['Blue', 'Green', 'Red']

Summary

Python dir() is a convinience function to determine the available attributes of an object or the attributes of local scope.

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

By admin

Leave a Reply

%d bloggers like this: