Debugging is a vital part of software development. Python provides various tools to inspect, diagnose, and resolve issues in code effectively. Below are some essential debugging tools every Python developer should know.
import pdb
x = 10
y = 20
pdb.set_trace()
print(x + y)
def divide(a, b):
breakpoint()
return a / b
print(divide(10, 2))
import logging
logging.basicConfig(level=logging.DEBUG)
x = 5
logging.debug(f"x = {x}")
import traceback
try:
1 / 0
except Exception as e:
print("Error:", traceback.format_exc())
import warnings
warnings.warn("This is a warning message")
def calculate_area(radius):
assert radius > 0, "Radius must be positive"
return 3.14 * radius ** 2
print(calculate_area(5))
import faulthandler
faulthandler.enable()
import cProfile
def test():
total = 0
for i in range(1000):
total += i
return total
cProfile.run('test()')
# Run using: mprof run script.py and then mprof plot
from memory_profiler import profile
@profile
def compute():
a = [i for i in range(100000)]
return sum(a)
compute()
# Use kernprof -l script.py then python -m line_profiler script.py.lprof
@profile
def multiply():
total = 1
for i in range(1, 100):
total *= i
return total
multiply()