breakpoint()Uses Python's built-in breakpoint hook. By default this opens pdb in interactive runs.
Core Python debugging commands, traceback inspection, runtime introspection, and practical troubleshooting workflows.
Interactive debugging with built-in breakpoints and pdb.
breakpoint()Uses Python's built-in breakpoint hook. By default this opens pdb in interactive runs.
import pdb; pdb.set_trace()Useful when you want an explicit dependency-free breakpoint in scripts and older codebases.
python -m pdb app.pyStarts the debugger before the first line of the script and lets you step through execution.
python -m pdb app.py --env dev --port 8000nIn pdb, `n` runs the current line and stops at the next line in the same frame.
scuntillp variable_namepp complex_objectwu
db app.py:42Capture and inspect failures quickly.
import traceback
try:
risky_call()
except Exception:
traceback.print_exc()import traceback
try:
risky_call()
except Exception:
error_text = traceback.format_exc()import sys
try:
risky_call()
except Exception:
exc_type, exc_value, exc_tb = sys.exc_info()try:
parse_config()
except ValueError as exc:
raise RuntimeError("Invalid configuration") from excimport faulthandler
faulthandler.enable()python -X faulthandler app.pypython -Wd app.pypython -X dev app.pyInspect objects, frames, environment, and imports.
print(type(obj))
print(dir(obj))print(vars(obj))from pprint import pprint
pprint(payload)import inspect
print(inspect.signature(func))import inspect
print(inspect.getsource(func))import sys
for path in sys.path:
print(path)import package_name
print(package_name.__file__)import os
print(os.environ.get("APP_ENV"))Use structured, actionable logs for faster debugging.
import logging
logging.basicConfig(level=logging.DEBUG)
logging.debug("Starting debug run")import logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(levelname)s %(name)s %(message)s',
)import logging
logger = logging.getLogger(__name__)
try:
risky_call()
except Exception:
logger.exception("Request processing failed")import logging
base_logger = logging.getLogger(__name__)
logger = logging.LoggerAdapter(base_logger, {"request_id": request_id})
logger.info("Processing request")import time
start = time.perf_counter()
result = expensive_call()
elapsed = time.perf_counter() - start
print(f"Elapsed: {elapsed:.4f}s")python -m timeit "sum(range(1000))"Debug tests and isolate flaky or failing behavior.
pytest -xpytest --pdbpytest -spytest tests/test_api.py::test_create_userpytest --lfpytest -vv --showlocalspython -m unittest -v tests.test_serviceDistinguish slow code from broken code and inspect resource usage.
python -m cProfile app.pypython -m cProfile -s tottime app.pyimport cProfile
import pstats
profiler = cProfile.Profile()
profiler.enable()
expensive_call()
profiler.disable()
pstats.Stats(profiler).sort_stats('tottime').print_stats(20)import tracemalloc
tracemalloc.start()
# run code
snapshot = tracemalloc.take_snapshot()
for stat in snapshot.statistics('lineno')[:10]:
print(stat)import os
import psutil
process = psutil.Process(os.getpid())
print(process.memory_info())
print(process.cpu_percent(interval=1.0))Requires the third-party `psutil` package, but it is extremely useful for production debugging and local diagnostics.
Common debugging patterns for servers, workers, and async code.
PYTHONASYNCIODEBUG=1 python app.pyimport asyncio
async def main():
...
asyncio.run(main(), debug=True)python -m http.server 8000python -X importtime app.pyimport faulthandler
import signal
faulthandler.register(signal.SIGUSR1)After registering a signal, send `SIGUSR1` to the process to dump thread stack traces.