Back to Posts
Hand holding a magnifying glass over a cluttered desk, highlighting the intricate details on a five-dollar bill, illustrating the concept of close examination similar to how to analyze Python classes with the inspect module.

Inspect Module Guide for Python Classes

By Alyce Osbourne

Python’s dynamic nature not only makes it versatile and powerful but also allows developers to explore and understand objects and their environments thoroughly. By mastering a few key functions, you can uncover a wealth of information about the objects you’re working with, aiding in debugging, exploration, and understanding Python’s internals. Below, we’ll discuss a number of neat functions in detail and introduce you to the inspect module, an indispensable tool for diving deeper into Python objects.

dir() - Discovering attributes and methods

The dir() function is perhaps the most straightforward way to list all the attributes and methods of an object. It returns a sorted list of strings containing the names of the found attributes, including both built-in and custom-defined ones. As its name suggests, it returns the attributes in the object “Directory,” similar to listing the files in a file directory.

my_list = [1, 2, 3]
print(dir(my_list))

This will output a list of methods associated with Python lists, like append, count, pop, and many others. dir() is incredibly useful for quickly understanding what operations you can perform on an object.

help() - Understanding how to use objects

While dir() tells you what methods and attributes an object has, help() tells you how to use them. Calling help() on any Python object will display its docstring, providing a concise summary of the object and how to interact with it.

help(my_list)

This command will display detailed information about list objects, including an overview of list methods and their usage.

globals(), locals() and vars- Peeking into namespaces

globals(), locals(), and vars() functions allow you to view the namespaces in the form of a dictionary. This can be particularly useful for debugging or understanding the scope of variables at any point in your code.

  • globals() returns a dictionary of the current global symbol table.
  • locals() returns a dictionary of the current local symbol table.
  • vars() returns a dictionary; if no object is passed as an argument, it is equivalent to locals(); otherwise returns the object’s namespace.

Exploring the output of these functions helps you understand which variables and objects are accessible at various points in your code. This can be particularly useful when understanding nested scopes and closures.

def print_locals():
	x = 10
	print(locals())

class Example:
    def __init__(self, name):
        self.name = name

o = Example("Arjan")

print(globals())
print_locals()
print(vars(o))

Diving deeper with the inspect module

For those seeking to take their introspection a step further, the inspect module is a treasure trove. It provides several functions to retrieve information about live objects, such as modules, classes, methods, functions, tracebacks, and the Python frame stack.

Key features of the inspect module:

  • Getting the source code: With inspect.getsource(), you can view the source code of a function or method directly in your Python interpreter.
  • Inspecting callable: Use inspect.signature() to get the signature of a callable object and inspect.getargspec() for detailed information about its arguments.
  • Analyzing classes and inheritance: Functions like inspect.getmembers() and inspect.getmro() help you explore the members of a class and its method resolution order, respectively.
import inspect

def my_function(x, y):
    return x + y

print(inspect.signature(my_function))

This code will output (x, y), showing the parameters of my_function.

Final thoughts

By leveraging dir, help, globals, locals, and the inspect module, you can gain deep insights into Python objects and their operating environment. Whether you’re debugging, exploring new libraries, or simply curious about Python’s inner workings, these tools are invaluable companions on your journey through Python’s dynamic landscape. With practice, you’ll find these techniques indispensable for developing a deeper understanding of Python and becoming a more effective Python programmer.

Improve your code with my 3-part code diagnosis framework

Watch my free 30 minutes code diagnosis workshop on how to quickly detect problems in your code and review your code more effectively.

When you sign up, you'll get an email from me regularly with additional free content. You can unsubscribe at any time.

Recent posts