Behind the Curtain: Using Introspection to Understand Python Objects

2024-04-05

There are two main ways to find an object's methods in Python:

  1. Using the dir() function:

  2. Using the inspect module:

    • Python provides the inspect module for more advanced introspection.

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.




  1. IDEs and Interactive Environments:

  2. Documentation:

  3. 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


Enforcing Choices in Django Models: MySQL ENUM vs. Third-Party Packages

Understanding ENUMs and Django's ApproachMySQL ENUM: In MySQL, an ENUM data type restricts a column's values to a predefined set of options...


Unlocking Image Data: A Guide to Converting RGB Images to NumPy Arrays with Python

Import libraries:cv2: This imports the OpenCV library, which provides functions for image processing tasks.numpy: This imports the NumPy library...


Serving Files with Python: Alternative Methods to SimpleHTTPServer

In Python 2, the SimpleHTTPServer module provided a convenient way to start a basic HTTP server for development purposes...


Demystifying Decimal Places: Controlling How PyTorch Tensors Are Printed in Python

Understanding Floating-Point PrecisionComputers store numbers in binary format, which has limitations for representing real numbers precisely...


Beyond the Basics: Advanced Row Selection for Pandas MultiIndex DataFrames

MultiIndex DataFramesIn pandas, DataFrames can have a special type of index called a MultiIndex.A MultiIndex has multiple levels...


python introspection