Insert a built-in breakpoint
Pause execution and enter the configured debugger.
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.
Pause execution and enter the configured debugger.
breakpoint()Uses Python's built-in breakpoint hook. By default this opens pdb in interactive runs.
Classic explicit breakpoint using pdb.
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.
Pass normal program arguments when starting under pdb.
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_objectwNavigate the traceback to inspect caller frames.
u
dBreak on a file and line number from within the debugger.
b app.py:42Capture and inspect failures quickly.
Dump the active exception traceback in an except block.
import traceback
try:
risky_call()
except Exception:
traceback.print_exc()import traceback
try:
risky_call()
except Exception:
error_text = traceback.format_exc()Access exception type, value, and traceback explicitly.
import sys
try:
risky_call()
except Exception:
exc_type, exc_value, exc_tb = sys.exc_info()Chain exceptions to keep original failure context.
try:
parse_config()
except ValueError as exc:
raise RuntimeError("Invalid configuration") from excPrint Python tracebacks on fatal errors like segfaults.
import faulthandler
faulthandler.enable()Turn on fatal error tracebacks without code changes.
python -X faulthandler app.pypython -Wd app.pyEnable extra runtime checks and debug-friendly behavior.
python -X dev app.pyInspect objects, frames, environment, and imports.
Quickly see what an object is and what it exposes.
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)Confirm which module file was actually imported.
import package_name
print(package_name.__file__)Print environment values affecting program behavior.
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',
)Emit the stack trace automatically in an except block.
import logging
logger = logging.getLogger(__name__)
try:
risky_call()
except Exception:
logger.exception("Request processing failed")Add contextual identifiers that make debugging easier.
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")Measure a small expression from the command line.
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 --lfReveal local state in failing assertions and exceptions.
pytest -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)Capture memory allocation snapshots.
import tracemalloc
tracemalloc.start()
# run code
snapshot = tracemalloc.take_snapshot()
for stat in snapshot.statistics('lineno')[:10]:
print(stat)Check runtime resource usage from inside the process.
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)Serve files locally to reproduce client behavior.
python -m http.server 8000python -X importtime app.pyUseful when an app appears hung or deadlocked.
import faulthandler
import signal
faulthandler.register(signal.SIGUSR1)After registering a signal, send `SIGUSR1` to the process to dump thread stack traces.