dir() function in Python

The dir() function lists the attributes of a Python Object. Attributes include both developer defined and the python implementation defined attributes.

Built-in Functions Updated 4 Mar 2017 2 min read

Function Name

dir

Function Signature

dir([object])

Function Overview

  • The dir() function returns a list of attributes of an object. The list returned may not be the complete list of attributes.

  • If the parameter 'object' is omitted, dir() returns the list of names in the current scope.

  • Every object in Python has '0' to 'n' number of attributes defined for it, by the developer.

  • Apart from the attributes defined be the developers, every python object also has several special attributes that are defined by the implementation as relevant to the object.

  • The dir() function returns the special attributes of the object as well – however not all the special attributes are returned by the dir() function.

  • If an object has the __dir__() method implemented, the attributes are returned as per the iterable returned by the __dir__() method.

  • Python allows instance attributes to be computed and returned from special functions __getattr__() and __getattribute__() as well. The implementation of __dir__() must return the list of attributes in accordance with the __getattr__() and __getattribute__().

Example 1 – Without __dir__() being overridden

python
class Student:

    def __init__(self, firstName, lastName, id):

        self.firstName  = firstName

        self.lastName   = lastName

        self.id         = id

    def __dir__(self):

        return (self.id,)

s1 = Student("John", "Adams", "01")

print(dir(s1))

Output

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__', 'firstName', 'id', 'lastName']

In the above output python defined attributes for the object s1 are listed by the dir() function followed by the developer defined attributes – firstName, id and lastName.

Example 2 – With __dir__() being overridden

python
class Student:

    def __init__(self, firstName, lastName, id):

        self.firstName  = firstName

        self.lastName   = lastName

        self.id         = id

    def __dir__(self):

         return self.__dict__.keys()

s1 = Student("John", "Adams", "01")

print(dir(s1))

Output:

Output
['firstName', 'id', 'lastName']