Practical Debug Methods
Advanced Debugging Techniques
Tracing Function Calls
Python provides powerful tools for tracing function execution and understanding program flow:
import sys
def trace_calls(frame, event, arg):
if event == 'call':
print(f"Calling function: {frame.f_code.co_name}")
return trace_calls
sys.settrace(trace_calls)
def example_function(x):
return x * 2
example_function(5)
Debugging Complex Data Structures
Pretty Printing
import pprint
complex_data = {
'users': [
{'name': 'Alice', 'age': 30},
{'name': 'Bob', 'age': 25}
],
'settings': {
'debug': True,
'log_level': 'INFO'
}
}
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(complex_data)
Interactive Debugging Methods
Method |
Description |
Use Case |
pdb |
Python Debugger |
Interactive step-by-step debugging |
ipdb |
IPython Debugger |
Enhanced debugging with IPython features |
breakpoint() |
Built-in debugging |
Modern Python debugging method |
Using pdb for Interactive Debugging
import pdb
def complex_calculation(a, b):
pdb.set_trace() ## Debugger breakpoint
result = a * b
return result
complex_calculation(10, 20)
Debugging Workflow
graph TD
A[Identify Problem] --> B[Select Debugging Method]
B --> |Simple Issues| C[Print Debugging]
B --> |Complex Logic| D[Interactive Debugger]
B --> |Performance| E[Profiling Tools]
C --> F[Analyze Output]
D --> F
E --> F
Error Tracking and Exceptions
Custom Exception Handling
def debug_exception_handler(exc_type, exc_value, exc_traceback):
print("An error occurred:")
print(f"Type: {exc_type}")
print(f"Value: {exc_value}")
import sys
sys.excepthook = debug_exception_handler
Timing Decorator
import time
def timeit(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} took {end - start} seconds")
return result
return wrapper
@timeit
def slow_function():
time.sleep(2)
slow_function()
Conclusion
Mastering practical debugging methods is crucial for efficient Python development. LabEx recommends practicing these techniques to improve your problem-solving skills and code quality.