The dir() function returns a list of all attributes and methods available for an object. It’s useful for exploring objects, debugging, and understanding built-in methods.
Example
x = [1, 2, 3]
print(dir(x))
This shows all methods and attributes available for a list, like append(), pop(), etc.
Syntax
dir(object) # Returns a list of available attributes and methods
- object → The object to inspect.
- Returns → A list of strings (method/attribute names).
If no object is passed, dir() returns all built-in names in the current scope.
print(dir()) # Shows all global variables and functions
1. Checking Methods of a Data Type
dir() helps you see what functions are available for an object.
text = "hello"
print(dir(text))
You’ll see methods like 'upper', 'lower', 'replace', 'split' – all functions you can use on a string.
2. Exploring Custom Classes
Use dir() to check what’s inside a class.
class Person:
def __init__(self, name):
self.name = name
def greet(self):
return "Hello"
print(dir(Person))
It shows built-in methods (__init__, __str__) and user-defined ones (greet).
3. Finding Available Methods for Modules
Want to see what functions a module provides?
import math
print(dir(math))
This lists functions like 'sqrt', 'cos', 'log', etc.
4. Using dir() for Debugging
If you’re unsure about an object’s available properties, dir() helps.
obj = {"key": "value"}
print(dir(obj))
This reveals dictionary-specific methods like keys(), values(), get(), etc.
Key Notes
- ✔ Shows all available attributes and methods – great for learning about objects.
- ✔ Works on built-in types, user-defined classes, and modules.
- ✔ Helps with debugging – quickly see what functions an object supports.
- ✔ No argument? Lists all names in the current scope – useful for checking variables.
By using dir(), you can explore objects dynamically and understand how to work with them efficiently. 🚀