Behind the Curtain: Using Introspection to Understand Python Objects
There are two main ways to find an object's methods in Python:
-
Using the dir() function:
-
Using the inspect module:
- Python provides the
inspect
module for more advanced introspection.
- Python provides the
Here's an example:
class MyClass:
def method1(self):
print("I'm method 1")
def method2(self):
print("I'm method 2")
obj = MyClass()
# Using dir()
print(dir(obj)) # This will print all attributes and methods
# Using inspect
import inspect
methods = inspect.getmembers(obj, inspect.ismethod)
for name, method in methods:
print(name) # This will print only method names
Introspection helps write flexible and generic code. For instance, a function can take any object and use dir()
or inspect
to discover its available methods and call them dynamically.
Using dir():
class MyClass:
def method1(self):
print("I'm method 1")
def method2(self):
print("I'm method 2")
obj = MyClass()
# Get all attributes and methods using dir()
all_members = dir(obj)
# Print all members (might include non-methods)
print("All members:", all_members)
# You can manually filter methods if needed (not ideal for large lists)
methods = [member for member in all_members if callable(getattr(obj, member))]
print("Methods only (manual filtering):", methods)
Using inspect:
class MyClass:
def method1(self):
print("I'm method 1")
def method2(self):
print("I'm method 2")
obj = MyClass()
import inspect
# Get all members using inspect.getmembers()
all_members = inspect.getmembers(obj)
# Filter methods using inspect.ismethod()
methods = [member[0] for member in all_members if inspect.ismethod(member[1])]
print("Methods only (using inspect):", methods)
These examples demonstrate both approaches. dir()
is simpler but returns everything, while inspect
offers more control and filtering capabilities. Choose the method that best suits your needs.
-
IDEs and Interactive Environments:
-
Documentation:
-
Context-Specific Exploration:
Here's a quick example of using hasattr
:
class MyClass:
def method1(self):
print("I'm method 1")
def method2(self):
print("I'm method 2")
obj = MyClass()
# Check if specific methods exist
if hasattr(obj, "method1"):
obj.method1()
if hasattr(obj, "unknown_method"):
print("Unknown method doesn't exist")
Remember, dir()
and inspect
are the core methods for programmatic introspection, but these complementary approaches can be valuable tools during development and exploration.
python introspection