Skip to main content

Basic Debugging in Python

For when you can't use a full-fledged debugger, here are some basic debugging techniques in Python:

  1. dir()

Lists all the attributes of an object. This can help you understand the structure of the object and its attributes.

print(dir(object))
  1. vars()

Prints the __dict__ attribute of an object. This can help you see the attributes and their values for an object.

class MyClass:
def __init__(self):
self.name = "Python"
self.version = 3.12


my_obj = MyClass()
print(vars(my_obj))
  1. pprint()

When dealing with complex data structures like nested dictionaries, the pprint module helps you pretty-print them in a more readable format.

from pprint import pprint

data = {'name': 'Python', 'features': ['dynamic', 'interpreted', 'high-level']}
pprint(data)

  1. inspect module

The inspect module provides functions for examining the runtime objects in Python. You can use it to get information about classes, functions, and tracebacks.

import inspect


def my_function():
return "Hello, World!"


# Get all members of the function
print(inspect.getmembers(my_function))

# Get the source code of the function
print(inspect.getsource(my_function))