dir() function in Python (original) (raw)
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__.