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.
dir(object)
Parameter
Return Value
dir() Without ArgumentsIf 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
a, b) and other built-in names available in the current environment.dir() With an Objectdir() 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
text.Example:
print(text.upper())
Output:
PYTHON
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]
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
sqrt, pi, and factorial.Example:
print(math.sqrt(25))
Output:
5.0
dir()The dir() function is useful for:
For example, when using a new library, dir() helps discover available functions.
dir() is a built-in Python function used to list attributes and methods of objects.