The dir() function is a built-in Python tool used to list the attributes (like methods, variables, etc.) of an object. It helps inspect modules, classes, functions, and even user-defined objects during development and debugging.
Syntax
dir([object])
Parameters:
- object (optional): Any Python object (like list, dict, class, module, etc.)
Return Type: A list of names (strings) representing the attributes of the object or current scope.
Behavior
- Without arguments: Lists names in the current local scope.
- With modules: Lists all available functions, classes, and constants.
- With user-defined objects: Lists all attributes, including user-defined ones (if __dir__ is defined).
- With built-in objects: Lists all valid attributes and methods.
Examples dir() Function
Example 1: No Parameters Passed
In this example, we are using the dir() function to list object attributes and methods in Python. It provides a demonstration for exploring the available functions and objects in our Python environment.
Python
print(dir())
import random
import math
print(dir())
Output:
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'traceback']
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'math', 'random', 'traceback']
Explanation:
- dir() lists names in the current local scope.
- Notice that after importing modules, the list includes random, math, etc, which were not present before importing them.
Example 2: Module Object Passed
This example demonstrates how dir() can explore all the attributes inside a module like random.
Python
import random
print("Attributes in random module:")
print(dir(random))
Output:
Attributes in random module:
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_ONE', '_Sequence', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_accumulate', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_fabs', '_floor', '_index', '_inst', '_isfinite', '_lgamma', '_log', '_log2', '_os', '_pi', '_random', '_repeat', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'binomialvariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randbytes', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
Explanation: Passing random lists all constants, functions, and classes available in the module
Example 3. When a List Object is Passed as Parameter
Here, we pass a list and a dictionary to dir() to explore their available methods.
Python
geeks = ["geeksforgeeks", "gfg", "Computer Science",
"Data Structures", "Algorithms" ]
d = {}
print(dir(geeks))
print(dir(d))
Output:
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__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']
['__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__ior__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__or__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__ror__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
Explanation:
- dir(my_list) returns all methods available to a list (e.g., append, sort, etc.)
- dir(my_dict) returns methods for dictionaries (e.g., keys, values, etc.)
Example 4. When User Defined Objects are Passed as Parameters
You can define your own class and customize what dir() returns using the __dir__() method.
Python
class Cart:
def __dir__(self):
return ['item', 'price', 'quantity']
c = Cart()
print(dir(c))
Output['item', 'price', 'quantity']
Explanation:
- Cart class defines a custom __dir__() method.
- dir(c) returns the list defined inside __dir__.
Also Read: __dir__(), objects.
Similar Reads
chr() Function in Python chr() function returns a string representing a character whose Unicode code point is the integer specified. chr() Example: Python3 num = 97 print("ASCII Value of 97 is: ", chr(num)) OutputASCII Value of 97 is: a Python chr() Function Syntaxchr(num) Parametersnum: an Unicode code integerRet
3 min read
Python Built in Functions Python is the most popular programming language created by Guido van Rossum in 1991. It is used for system scripting, software development, and web development (server-side). Web applications can be developed on a server using Python. Workflows can be made with Python and other technologies. Databas
6 min read
Python print() function The python print() function as the name suggests is used to print a python object(s) in Python as standard output. Syntax: print(object(s), sep, end, file, flush) Parameters: Object(s): It can be any python object(s) like string, list, tuple, etc. But before printing all objects get converted into s
2 min read
sum() function in Python The sum of numbers in the list is required everywhere. Python provides an inbuilt function sum() which sums up the numbers in the list. Pythonarr = [1, 5, 2] print(sum(arr))Output8 Sum() Function in Python Syntax Syntax : sum(iterable, start) iterable : iterable can be anything list , tuples or dict
3 min read
Python open() Function The Python open() function is used to open internally stored files. It returns the contents of the file as Python objects. Python open() Function SyntaxThe open() function in Python has the following syntax: Syntax: open(file_name, mode)Â Parameters: file_name: This parameter as the name suggests, i
3 min read