Tutorial Study Image

Python dir()

The dir function takes an object as input and returns all attributes or properties of the object. The attributes are returned in the form of a list.


dir(object) # object is any python object 
 

dir() Parameters:

The dir() function takes an object as a parameter. Built-in objects and user-defined objects can be passed as parameters. Even if no parameter is passed it will not throw an error.

Parameter Description Required / Optional
object Any Python object whose attributes to be returned Optional

dir() Return Value

The function returns all attributes of the object passed, the built in attributes are also returned. If no parameter passed, names in the current local scope are returned.

Input Return Value
None returns a list of names in the current local scope.
object Returns the attributes of the object passed

Examples of dir() method in Python

Example 1: Passing a bulit in object


letters = {'a':1, 'b':2, 'c':3}
# Dictionary is a built in object in python 
print(dir(letters))
 

Output:

[' 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']

Example 2: Passing no parameter


print(dir())
 

Output:

['    annotations    ', '    builtins    ', '    cached    ', '    doc    ', '    file    ', '    loader    ', '  name ', ' package ', ' spec ']

Example 3: Passing a user defined object


class Student:
name = "Ram" 
age = 22
course = "Bachelors" 
Student1 = Student() 
print(dir(Student1))
 

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 ', 'age', 'course', 'name']
# The built in attributes of class is also returned along with the user defined attributes