dir() Builtin Function


Python - dir()

Python dir() builtin function is used to get all the properties and methods in a given object as a list.

In this tutorial, you will learn the syntax of dir() function, and then its usage with the help of example programs.

Syntax

The syntax of dir() function is

dir(object)

where

ParameterDescription
objectAny valid Python object.

Examples

1. dir() with user defined object

In the following program, we define a class Fruit, and create an object apple of type Fruit. We use dir() function and print all the methods and properties of the apple object.

Python Program

class Fruit:
    name = ''
    quantity = ''
    description = ''
    
    def __init__(self, name, quantity, description):
        self.name = name
        self.quantity = quantity
        self.description = description

apple = Fruit('Apple', '58', 'Good for health.')
output = dir(apple)
print(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__', 'description', 'name', 'quantity']

2. dir() with list object as argument

In the following program, we take a list object fruits, and get all the methods and properties for this object.

Python Program

fruits = ['apple', 'banana', 'cherry']
output = dir(fruits)
print(output)

Output

['__add__', '__class__', '__class_getitem__', '__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']

Summary

In this tutorial of Python Examples, we learned the syntax of dir() function, and how to get the list of all methods and properties using dir() function, with examples.