Notes

`dir()` Function in Python [ English ]

< Prev Next >

1. Introduction

The dir() function in Python is a built-in function used to list the names of attributes and methods of an object. It helps programmers explore the properties, variables, and functions available in modules, classes, or objects.

dir() is commonly used in interactive Python sessions and during program development to understand what operations can be performed on a particular object.

2. Syntax

dir(object)

Parameter

Return Value

3. Using dir() Without Arguments

If dir() is called without any argument, it returns the list of names defined in the current local scope.

a = 10
b = 20

print(dir())

Output (example)

['__annotations__', '__builtins__', '__name__', 'a', 'b']

Explanation

4. Using dir() With an Object

dir() can be used to see all available methods and attributes of an object.

text = "Python"

print(dir(text))

Output (partial)

['capitalize', 'casefold', 'center', 'count', 'encode',
 'endswith', 'find', 'format', 'index', 'join', 'lower', 'replace']

Explanation

Example:

print(text.upper())

Output:

PYTHON

5. Example with List Object

numbers = [1, 2, 3]

print(dir(numbers))

Output (partial)

['append', 'clear', 'copy', 'count', 'extend', 'index',
 'insert', 'pop', 'remove', 'reverse', 'sort']

Explanation

Example usage:

numbers.append(4)
print(numbers)

Output:

[1, 2, 3, 4]

6. Example with a Module

dir() can also be used to see the contents of a module.

import math

print(dir(math))

Output (partial)

['acos', 'asin', 'atan', 'ceil', 'cos', 'factorial',
 'floor', 'log', 'pi', 'pow', 'sqrt', 'tan']

Explanation

Example:

print(math.sqrt(25))

Output:

5.0

7. Practical Use of dir()

The dir() function is useful for:

For example, when using a new library, dir() helps discover available functions.

8. Summary

< Prev Next >