The dir()
function is a built-in Python function used to list all attributes and methods available in an object, module, or class. It helps developers explore and debug Python objects.
๐น Syntax
dir(object) # Returns a list of attributes and methods of the object
- If no object is passed,
dir()
returns the list of all available names in the current scope. - If an object (module, class, function, etc.) is passed, it returns the list of available attributes and methods for that object.
๐น Example 1: Using dir()
Without Arguments
print(dir()) # Lists all available names in the current scope
๐น Output (Example)
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
๐น Example 2: Using dir()
With a Module
import math
print(dir(math)) # Lists all functions and attributes in the math module
๐น Output (Truncated)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'asin', 'atan', 'ceil', 'cos', 'exp', 'factorial', 'floor', 'log', 'pi', 'sqrt']
๐ฏ This helps find available functions like sqrt()
, log()
, and pi
.
๐น Example 3: Using dir()
With an Object
class Sample:
def method1(self):
pass
def method2(self):
pass
obj = Sample()
print(dir(obj)) # Lists attributes and methods of the Sample class
๐น Output (Truncated)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__ne__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'method1', 'method2']
๐ The list includes special methods (__init__
, __str__
, etc.) and user-defined methods (method1()
, method2()
).
๐น Example 4: Filtering Attributes
If you only want to see user-defined attributes, you can filter out built-in methods:
attributes = [attr for attr in dir(obj) if not attr.startswith('__')]
print(attributes) # Output: ['method1', 'method2']
๐น Example 5: Using dir()
on Built-in Types
๐ dir()
on a List
print(dir(list))
๐น Output (Truncated)
['append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
๐ฏ This helps us find methods like .append()
, .sort()
, .pop()
, etc.
๐น Summary
Use Case | Example | Purpose |
---|---|---|
Get current scope | dir() |
Lists all variables in the current environment |
Inspect module | dir(math) |
Lists all functions & attributes of math |
Inspect object | dir(obj) |
Lists all methods & attributes of obj |
Inspect list | dir(list) |
Shows available list methods |
Filter attributes | [x for x in dir(obj) if not x.startswith('__')] |
Shows only user-defined attributes |
๐ฏ Key Takeaways
โ
dir()
is useful for exploring Python objects.
โ
It helps discover available methods and attributes in a module or class.
โ
Filtering out __
methods gives user-defined attributes.
Do you need more real-world applications of dir()
? ๐
Leave a Reply