Skip to content

API Reference

Technical reference for public modules, CLI commands, and internal core subsystems.

Public Interface

Public modules and entrypoints designed for direct consumption:

Package Root

debug_dojo

Opinionated Python debugger and runner powered by dpdb and Rich.

Importing debug_dojo.install injects debugging tools into Python's builtins:

import debug_dojo.install

b()

This configures dpdb as the active debugger, installs debugging helpers (b(), p(), i(), c()), and triggers a breakpoint.

You can also invoke set_trace(), post_mortem(), or pm() directly:

import debug_dojo

debug_dojo.set_trace()

Or run target scripts, modules, or commands directly from the CLI:

$ uvx debug-dojo target_script.py value_1

Modules:

Name Description
cli

Command-line interface for running targets with the dpdb debugger.

install

Install opinionated debugging tools into the current Python runtime.

Functions:

Name Description
pm

Enter dpdb post-mortem debugging on the last unhandled exception.

post_mortem

Enter post-mortem debugging on the given or active exception traceback.

set_trace

Enter the internal DPDB debugger at the given or calling stack frame.

pm

pm() -> None

Enter dpdb post-mortem debugging on the last unhandled exception.

Source code in src/debug_dojo/_core/debugger/session.py
def pm() -> None:
    """Enter `dpdb` post-mortem debugging on the last unhandled exception."""
    last_exc = getattr(sys, "last_exc", None)
    tb = (
        last_exc.__traceback__
        if isinstance(last_exc, BaseException)
        else getattr(sys, "last_traceback", None)
    )
    post_mortem(tb)

post_mortem

post_mortem(tb: TracebackType | None = None) -> None

Enter post-mortem debugging on the given or active exception traceback.

Args: tb (TracebackType | None): Traceback to inspect (defaults to active exc_info).

Source code in src/debug_dojo/_core/debugger/session.py
def post_mortem(tb: TracebackType | None = None) -> None:
    """Enter post-mortem debugging on the given or active exception traceback.

    Args:
        tb (TracebackType | None): Traceback to inspect (defaults to active exc_info).

    """
    wrap_sys_excepthook()
    pdb_instance = _init_pdb()
    pdb_instance.reset()
    target_tb = sys.exc_info()[2] if tb is None else tb
    if target_tb is not None:
        console = (
            pdb_instance._console()  # ruff: ignore[private-member-access] -- _console is internal to DojoPdb in this package
            if isinstance(pdb_instance, DojoPdb)
            else Console(file=getattr(pdb_instance, "stdout", sys.stdout))
        )
        _render_post_mortem_banner(target_tb, console)
        pdb_instance.interaction(None, target_tb)

set_trace

set_trace(frame: FrameType | None = None) -> None

Enter the internal DPDB debugger at the given or calling stack frame.

Args: frame (FrameType | None): Target stack frame. Defaults to the caller's frame.

Source code in src/debug_dojo/_core/debugger/session.py
def set_trace(frame: FrameType | None = None) -> None:
    """Enter the internal DPDB debugger at the given or calling stack frame.

    Args:
        frame (FrameType | None): Target stack frame. Defaults to the caller's frame.

    """
    wrap_sys_excepthook()
    target_frame = (
        sys._getframe().f_back  # ruff: ignore[private-member-access] -- sys._getframe is required to resolve the caller stack frame
        if frame is None
        else frame
    )
    pdb_instance = _init_pdb()
    shell = getattr(pdb_instance, "shell", None)
    if shell is not None and hasattr(shell, "restore_sys_module_state"):
        shell.restore_sys_module_state()
    pdb_instance.set_trace(target_frame)

In-Code Installer

debug_dojo.install

Install opinionated debugging tools into the current Python runtime.

Command Line Interface

debug_dojo.cli

Command-line interface for running targets with the dpdb debugger.

Classes:

Name Description
CliArgs

Parsed command-line arguments for Dojo.

CliResult

Result of running a CLI invocation in a captured buffer.

CliRunner

Runner for invoking dojo CLI commands in test and automation environments.

Functions:

Name Description
get_version

Return the package version string.

render_help

Render the formatted CLI help screen using Rich panels.

parse_cli_args

Parse raw CLI argument strings into structured CliArgs.

cli

Execute the dojo command-line interface.

main

Entry point for the debug-dojo and dojo CLI commands.

CliArgs dataclass

CliArgs(
    target: str | None = None,
    target_args: tuple[str, ...] = (),
    breaks: tuple[str, ...] = (),
    show_help: bool = False,
    show_version: bool = False,
    error: str | None = None,
)

Parsed command-line arguments for Dojo.

Attributes: target: Target script, module, or executable to debug. target_args: Command-line arguments forwarded directly to the target. breaks: Initial breakpoint expressions armed before running the target. show_help: Flag indicating whether the help screen should be displayed. show_version: Flag indicating whether version info should be displayed. error: Validation error message if argument parsing failed.

CliResult dataclass

CliResult(exit_code: int, output: str)

Result of running a CLI invocation in a captured buffer.

Attributes: exit_code: Exit status code. output: Captured combined standard and error output text.

CliRunner

CliRunner(env: Mapping[str, str] | None = None)

Runner for invoking dojo CLI commands in test and automation environments.

Args: env (Mapping[str, str] | None): Environment variables to inject during runs.

Methods:

Name Description
invoke

Invoke app with args, capturing combined standard and error output.

Source code in src/debug_dojo/cli.py
def __init__(self, env: Mapping[str, str] | None = None) -> None:
    """Initialize runner with optional environment variables.

    Args:
        env (Mapping[str, str] | None): Environment variables to inject during runs.

    """
    self.env = dict(env) if env is not None else {}

invoke

invoke(app: Callable[..., int], args: Sequence[str] | None = None) -> CliResult

Invoke app with args, capturing combined standard and error output.

Args: app (Callable[..., int]): The CLI entrypoint function. args (Sequence[str] | None): Arguments passed to app.

Returns: CliResult: Exit code and captured output.

Source code in src/debug_dojo/cli.py
def invoke(
    self,
    app: Callable[..., int],
    args: Sequence[str] | None = None,
) -> CliResult:
    """Invoke `app` with `args`, capturing combined standard and error output.

    Args:
        app (Callable[..., int]): The CLI entrypoint function.
        args (Sequence[str] | None): Arguments passed to `app`.

    Returns:
        CliResult: Exit code and captured output.

    """
    buf = io.StringIO()
    old_env = os.environ.copy()
    os.environ.update(self.env)
    try:
        with redirect_stdout(buf), redirect_stderr(buf):
            exit_code = app(args, stdout=buf, stderr=buf)
    except SystemExit as exc:
        code = exc.code
        exit_code = code if isinstance(code, int) else 0 if code is None else 1
    finally:
        os.environ.clear()
        os.environ.update(old_env)
    return CliResult(exit_code=exit_code, output=buf.getvalue())

get_version

get_version() -> str

Return the package version string.

Returns: str: Installed package version of debug-dojo, or fallback "0.10.0".

Source code in src/debug_dojo/cli.py
def get_version() -> str:
    """Return the package version string.

    Returns:
        str: Installed package version of debug-dojo, or fallback `"0.10.0"`.

    """
    try:
        return version("debug-dojo")
    except PackageNotFoundError:
        return "0.10.0"

render_help

render_help(console: Console) -> None

Render the formatted CLI help screen using Rich panels.

Args: console (Console): Target Rich console for output rendering.

Source code in src/debug_dojo/cli.py
def render_help(console: Console) -> None:
    """Render the formatted CLI help screen using Rich panels.

    Args:
        console (Console): Target Rich console for output rendering.

    """
    console.print()
    console.print(
        " [bold]Usage:[/bold] [cyan]dojo[/cyan] [dim][OPTIONS][/dim] "
        "[cyan][target][/cyan] [dim][target_args...][/dim]"
    )
    console.print()
    console.print(" Run a Python script, module, or command with the dpdb debugger.")
    console.print()

    arg_table = Table(box=None, show_header=False, pad_edge=False, expand=True)
    arg_table.add_column("name", style="bold cyan", width=16, no_wrap=True)
    arg_table.add_column("desc", style="default")
    arg_table.add_row("target", "The target script, module, or command to debug.")
    arg_table.add_row(
        "target_args",
        "Arguments forwarded directly to the target program.",
    )
    console.print(
        Panel(arg_table, title="Arguments", title_align="left", box=box.ROUNDED)
    )

    opt_table = Table(box=None, show_header=False, pad_edge=False, expand=True)
    opt_table.add_column("opt", style="bold cyan", width=22, no_wrap=True)
    opt_table.add_column("desc", style="default")
    opt_table.add_row(
        "-b, --break <loc>",
        "Set a breakpoint (line, file:line, or function).",
    )
    opt_table.add_row("-v, --version", "Show version and exit.")
    opt_table.add_row("-h, --help", "Show this message and exit.")
    options_panel = Panel(
        opt_table,
        title="Options",
        title_align="left",
        box=box.ROUNDED,
    )
    console.print(options_panel)
    console.print()

parse_cli_args

parse_cli_args(args: Sequence[str]) -> CliArgs

Parse raw CLI argument strings into structured CliArgs.

Args: args (Sequence[str]): List of command-line argument strings.

Returns: CliArgs: Structured parsed CLI options and arguments.

Source code in src/debug_dojo/cli.py
def parse_cli_args(args: Sequence[str]) -> CliArgs:
    """Parse raw CLI argument strings into structured `CliArgs`.

    Args:
        args (Sequence[str]): List of command-line argument strings.

    Returns:
        CliArgs: Structured parsed CLI options and arguments.

    """
    breaks: list[str] = []
    idx = 0
    while idx < len(args):
        next_idx, result = _process_arg_step(args[idx], args, idx, breaks)
        if result is not None:
            return result
        idx = next_idx

    return CliArgs(breaks=tuple(breaks))

cli

cli(
    args: Sequence[str] | None = None,
    stdout: TextIO | None = None,
    stderr: TextIO | None = None,
) -> int

Execute the dojo command-line interface.

Args: args (Sequence[str] | None): Argument list. Defaults to sys.argv[1:]. stdout (TextIO | None): Stream for standard output. Defaults to sys.stdout. stderr (TextIO | None): Stream for error output. Defaults to sys.stderr.

Returns: int: Exit status code (0 for success, non-zero for errors).

Source code in src/debug_dojo/cli.py
def cli(
    args: Sequence[str] | None = None,
    stdout: TextIO | None = None,
    stderr: TextIO | None = None,
) -> int:
    """Execute the `dojo` command-line interface.

    Args:
        args (Sequence[str] | None): Argument list. Defaults to `sys.argv[1:]`.
        stdout (TextIO | None): Stream for standard output. Defaults to `sys.stdout`.
        stderr (TextIO | None): Stream for error output. Defaults to `sys.stderr`.

    Returns:
        int: Exit status code (0 for success, non-zero for errors).

    """
    out_file = sys.stdout if stdout is None else stdout
    err_file = sys.stderr if stderr is None else stderr
    out_console = Console(
        file=out_file,
        highlight=False,
        soft_wrap=True,
        legacy_windows=False,
    )
    err_console = Console(
        file=err_file,
        highlight=False,
        soft_wrap=True,
        legacy_windows=False,
    )

    raw_args = list(args) if args is not None else sys.argv[1:]
    if not raw_args:
        render_help(out_console)
        return 0

    return _dispatch_parsed(parse_cli_args(raw_args), out_console, err_console)

main

main() -> None

Entry point for the debug-dojo and dojo CLI commands.

Source code in src/debug_dojo/cli.py
def main() -> None:
    """Entry point for the `debug-dojo` and `dojo` CLI commands."""
    sys.exit(cli())

Architecture Dependency Graph

The internal module boundaries and import hierarchy are strictly enforced by Tach:

graph TD
    debug_dojo --> debug_dojo._core
    debug_dojo.__main__ --> debug_dojo.cli
    debug_dojo.cli
    debug_dojo._core

Internal Core Subsystems

Detailed API documentation for internal modules isolated under debug_dojo._core:

Debugger Subsystem

debug_dojo._core.debugger.debugger

IPython-powered interactive debugger (DojoPdb) with Rich enhancements.

Classes:

Name Description
DojoPdb

Enhanced IPython debugger with Rich inspection and live frame context.

DojoPdb

DojoPdb(
    *args: object,
    pt_session_options: Mapping[str, object] | None = None,
    **kwargs: object,
)

Bases: TerminalPdb


              flowchart TD
              debug_dojo._core.debugger.debugger.DojoPdb[DojoPdb]

              

              click debug_dojo._core.debugger.debugger.DojoPdb href "" "debug_dojo._core.debugger.debugger.DojoPdb"
            

Enhanced IPython debugger with Rich inspection and live frame context.

Args: *args (object): Positional arguments forwarded to TerminalPdb. pt_session_options (Mapping[str, object] | None): Optional prompt_toolkit session options. **kwargs (object): Keyword arguments forwarded to TerminalPdb.

Methods:

Name Description
close

Close prompt_toolkit event loop and executor resources.

__del__

Ensure background loop and executor are closed on garbage collection.

message

Print a message to stdout unless suppressed.

stop_here

Return whether execution should stop at frame during stepping.

user_return

Handle function return events while skipping redundant or hidden returns.

emptyline

Repeat lastcmd on empty Enter only when it is a safe navigation command.

print_stack_entry

Print a stack entry with adaptive context lines and live variable banner.

print_stack_trace

Render a compact Rich call stack table followed by active frame context.

do_context

Set the number of source context lines shown on frame entry (context).

do_break

Set a breakpoint or render a Rich table of active breakpoints (b).

do_continue

Continue execution until next breakpoint (c), or evaluate c(...).

do_display

Add a watch expression or render a Rich table of watched expressions.

do_whatis

Display the type, MRO, and signature/size of an expression (whatis).

do_psource

Render syntax-highlighted source code for an object (psource).

displayhook

Render interactive REPL expression results with Rich pretty-printing.

do_p

Rich-print the value of an expression (p <expr>).

do_pp

Rich pretty-print the expanded value of an expression (pp <expr>).

do_pinfo

Provide detailed information about an object in a Rich panel (pinfo).

do_pinfo2

Provide extra detailed information about an object (pinfo2).

do_args

Display the argument list of the current function in a Rich table (a).

do_interact

Start an interactive IPython shell in the current frame (interact).

do_help

Display the categorized command reference table or help for a command (h).

Source code in src/debug_dojo/_core/debugger/debugger.py
@override
def __init__(
    self,
    *args: object,
    pt_session_options: Mapping[str, object] | None = None,
    **kwargs: object,
) -> None:
    """Initialize the DojoPdb debugger session.

    Args:
        *args (object): Positional arguments forwarded to `TerminalPdb`.
        pt_session_options (Mapping[str, object] | None): Optional
            `prompt_toolkit` session options.
        **kwargs (object): Keyword arguments forwarded to `TerminalPdb`.

    """
    self._last_paused_location = None
    self._last_printed_frame_id = None
    self._managed_underscore_frames = set()
    self._prev_locals_by_frame = {}
    self._suppress_message = False
    session_opts: dict[str, object] = {
        "bottom_toolbar": self._render_bottom_toolbar,
    }
    if pt_session_options is not None:
        session_opts.update(pt_session_options)
    super().__init__(
        *args,
        pt_session_options=session_opts,
        **kwargs,
    )
    self._full_context = self.context
    self.prompt = "dpdb> "

close

close() -> None

Close prompt_toolkit event loop and executor resources.

Source code in src/debug_dojo/_core/debugger/debugger.py
def close(self) -> None:
    """Close prompt_toolkit event loop and executor resources."""
    loop = getattr(self, "pt_loop", None)
    if loop is not None and not loop.is_closed():
        loop.close()
    executor = getattr(self, "thread_executor", None)
    if executor is not None:
        executor.shutdown(wait=False)

__del__

__del__() -> None

Ensure background loop and executor are closed on garbage collection.

Source code in src/debug_dojo/_core/debugger/debugger.py
def __del__(self) -> None:
    """Ensure background loop and executor are closed on garbage collection."""
    self.close()

message

message(msg: str) -> None

Print a message to stdout unless suppressed.

Args: msg (str): Message text to output.

Source code in src/debug_dojo/_core/debugger/debugger.py
@override
def message(self, msg: str) -> None:
    """Print a message to stdout unless suppressed.

    Args:
        msg (str): Message text to output.

    """
    if not self._suppress_message:
        super().message(msg)

stop_here

stop_here(frame: FrameType) -> bool

Return whether execution should stop at frame during stepping.

Args: frame (FrameType): Candidate stack frame.

Returns: bool: False when frame is hidden, otherwise superclass result.

Source code in src/debug_dojo/_core/debugger/debugger.py
@override
def stop_here(self, frame: FrameType) -> bool:
    """Return whether execution should stop at `frame` during stepping.

    Args:
        frame (FrameType): Candidate stack frame.

    Returns:
        bool: `False` when `frame` is hidden, otherwise superclass result.

    """
    if self.skip_hidden and self._hidden_predicate(frame):
        if is_runner_frame(frame):
            self.stopframe = getattr(self, "botframe", None)
            self.returnframe = None
            self.stoplineno = -1
        return False
    return bool(super().stop_here(frame))

user_return

user_return(frame: FrameType, return_value: object) -> None

Handle function return events while skipping redundant or hidden returns.

Args: frame (FrameType): Returning stack frame. return_value (object): Value returned by frame.

Source code in src/debug_dojo/_core/debugger/debugger.py
@override
def user_return(self, frame: FrameType, return_value: object) -> None:
    """Handle function return events while skipping redundant or hidden returns.

    Args:
        frame (FrameType): Returning stack frame.
        return_value (object): Value returned by `frame`.

    """
    if getattr(self, "_wait_for_mainpyfile", False):
        return
    if self.skip_hidden and self._hidden_predicate(frame):
        return
    if self._should_skip_return_pause(frame):
        self.set_step()
        return
    self._suppress_message = True
    try:
        super().user_return(frame, return_value)
    finally:
        self._suppress_message = False

emptyline

emptyline() -> bool

Repeat lastcmd on empty Enter only when it is a safe navigation command.

Returns: bool: Result of repeating lastcmd, or False when ignored.

Source code in src/debug_dojo/_core/debugger/debugger.py
@override
def emptyline(self) -> bool:
    """Repeat `lastcmd` on empty Enter only when it is a safe navigation command.

    Returns:
        bool: Result of repeating `lastcmd`, or `False` when ignored.

    """
    stripped = self.lastcmd.strip()
    cmd_name = stripped.split(maxsplit=1)[0] if stripped else ""
    if cmd_name in _REPEATABLE_COMMANDS:
        return bool(super().emptyline())
    return False

print_stack_entry

print_stack_entry(
    frame_lineno: tuple[FrameType, int], prompt_prefix: str = "\n-> "
) -> None

Print a stack entry with adaptive context lines and live variable banner.

Args: frame_lineno (tuple[FrameType, int]): Target (frame, lineno) pair. prompt_prefix (str): Prefix string forwarded to superclass.

Source code in src/debug_dojo/_core/debugger/debugger.py
@override
def print_stack_entry(
    self,
    frame_lineno: tuple[FrameType, int],
    prompt_prefix: str = "\n-> ",
) -> None:
    """Print a stack entry with adaptive context lines and live variable banner.

    Args:
        frame_lineno (tuple[FrameType, int]): Target `(frame, lineno)` pair.
        prompt_prefix (str): Prefix string forwarded to superclass.

    """
    frame, lineno = frame_lineno
    is_current = frame is getattr(self, "curframe", None)
    if is_current and id(frame) == self._last_printed_frame_id:
        self.context = min(self._full_context, STEP_CONTEXT_LINES)
    else:
        self.context = self._full_context
    frame_locals = cast(
        "MutableMapping[str, object]", self._get_frame_locals(frame)
    )
    has_return = "__return__" in frame_locals
    saved_return = frame_locals.pop("__return__", None) if has_return else None
    try:
        super().print_stack_entry(frame_lineno, prompt_prefix)
    finally:
        if has_return:
            frame_locals["__return__"] = saved_return
        self.context = self._full_context
    if is_current:
        self._last_printed_frame_id = id(frame)
        self._last_paused_location = (id(frame), lineno)
        self._render_frame_context_banner(frame, lineno)

print_stack_trace

print_stack_trace(context: int | None = None) -> None

Render a compact Rich call stack table followed by active frame context.

Args: context (int | None): Optional context line override for the active frame.

Source code in src/debug_dojo/_core/debugger/debugger.py
@override
def print_stack_trace(self, context: int | None = None) -> None:
    """Render a compact Rich call stack table followed by active frame context.

    Args:
        context (int | None): Optional context line override for the active frame.

    """
    del context
    console = self._console()
    table = _build_stack_table(
        self.stack,
        self.hidden_frames(self.stack),
        getattr(self, "curframe", None),
        skip_hidden=self.skip_hidden,
    )
    console.print(table)

do_context

do_context(context: str) -> None

Set the number of source context lines shown on frame entry (context).

Args: context (str): Positive integer number of lines.

Source code in src/debug_dojo/_core/debugger/debugger.py
@override
def do_context(self, context: str) -> None:
    """Set the number of source context lines shown on frame entry (`context`).

    Args:
        context (str): Positive integer number of lines.

    """
    super().do_context(context)
    self._full_context = self.context

do_break

do_break(arg: str, temporary: Literal[0, 1] | bool = 0) -> None

Set a breakpoint or render a Rich table of active breakpoints (b).

Args: arg (str): Breakpoint location/condition, or empty to list breakpoints. temporary (Literal[0, 1] | bool): Whether the breakpoint is temporary.

Source code in src/debug_dojo/_core/debugger/debugger.py
@override
def do_break(self, arg: str, temporary: Literal[0, 1] | bool = 0) -> None:
    """Set a breakpoint or render a Rich table of active breakpoints (`b`).

    Args:
        arg (str): Breakpoint location/condition, or empty to list breakpoints.
        temporary (Literal[0, 1] | bool): Whether the breakpoint is temporary.

    """
    if not arg.strip():
        active_bps = [bp for bp in bdb.Breakpoint.bpbynumber if bp is not None]
        console = self._console()
        if not active_bps:
            console.print("[dim]No breakpoints set.[/dim]")
            return
        console.print(_build_breakpoints_table(active_bps))
        return
    target_part, sep, cond_part = arg.partition(",")
    expr = target_part.strip()
    cond_str = cond_part.strip() if sep else None
    if self._try_set_callable_break(expr, cond_str, temporary=bool(temporary)):
        return
    super().do_break(arg, temporary)

do_continue

do_continue(arg: str) -> bool | None

Continue execution until next breakpoint (c), or evaluate c(...).

Args: arg (str): Command argument, forwarded to evaluator when c(...).

Returns: bool | None: Superclass return value, or None when executing c(...).

Source code in src/debug_dojo/_core/debugger/debugger.py
@override
def do_continue(self, arg: str) -> bool | None:
    """Continue execution until next breakpoint (`c`), or evaluate `c(...)`.

    Args:
        arg (str): Command argument, forwarded to evaluator when `c(...)`.

    Returns:
        bool | None: Superclass return value, or `None` when executing `c(...)`.

    """
    stripped = arg.strip()
    if stripped.startswith("(") and stripped.endswith(")"):
        self.default(f"c{stripped}")
        return None
    return super().do_continue(arg)

do_display

do_display(arg: str) -> None

Add a watch expression or render a Rich table of watched expressions.

Args: arg (str): Expression to watch, or empty to list active watches.

Source code in src/debug_dojo/_core/debugger/debugger.py
@override
def do_display(self, arg: str) -> None:
    """Add a watch expression or render a Rich table of watched expressions.

    Args:
        arg (str): Expression to watch, or empty to list active watches.

    """
    target_expr = arg.strip()
    frame = getattr(self, "curframe", None)
    if not target_expr:
        watches = self.displaying.get(frame, {}) if frame is not None else {}
        console = self._console()
        if not watches:
            console.print("[dim]No expressions are being displayed.[/dim]")
            return
        items = [(expr, self._getval_except(expr), True) for expr in watches]
        console.print(_build_variables_table("Watched Expressions", items))
        return
    super().do_display(target_expr)

do_whatis

do_whatis(arg: str) -> None

Display the type, MRO, and signature/size of an expression (whatis).

Args: arg (str): Expression string to inspect.

Source code in src/debug_dojo/_core/debugger/debugger.py
@override
def do_whatis(self, arg: str) -> None:
    """Display the type, MRO, and signature/size of an expression (`whatis`).

    Args:
        arg (str): Expression string to inspect.

    """
    target_expr = arg.strip()
    ok, val = self._eval_arg(target_expr)
    if ok:
        self._console().print(_build_whatis_panel(target_expr, val))

do_psource

do_psource(arg: str) -> None

Render syntax-highlighted source code for an object (psource).

Args: arg (str): Expression or symbol name whose source should be shown.

Source code in src/debug_dojo/_core/debugger/debugger.py
@override
def do_psource(self, arg: str) -> None:
    """Render syntax-highlighted source code for an object (`psource`).

    Args:
        arg (str): Expression or symbol name whose source should be shown.

    """
    target_expr = arg.strip()
    ok, val = self._eval_arg(target_expr)
    if not ok:
        return
    panel = _build_psource_panel(target_expr, val)
    if panel is None:
        self.error(f"Source code unavailable for {target_expr!r}.")
        return
    self._console().print(panel)

displayhook

displayhook(obj: object) -> None

Render interactive REPL expression results with Rich pretty-printing.

Args: obj (object): Evaluated expression value.

Source code in src/debug_dojo/_core/debugger/debugger.py
@override
def displayhook(self, obj: object) -> None:
    """Render interactive REPL expression results with Rich pretty-printing.

    Args:
        obj (object): Evaluated expression value.

    """
    if obj is not None:
        self._store_last_result(obj)
        rich_pprint(obj, console=self._console(), expand_all=True)

do_p

do_p(arg: str) -> None

Rich-print the value of an expression (p <expr>).

Args: arg (str): Expression string to evaluate and print.

Source code in src/debug_dojo/_core/debugger/debugger.py
@override
def do_p(self, arg: str) -> None:
    """Rich-print the value of an expression (`p <expr>`).

    Args:
        arg (str): Expression string to evaluate and print.

    """
    ok, val = self._eval_arg(arg)
    if ok:
        self._store_last_result(val)
        rich_pprint(val, console=self._console(), expand_all=False)

do_pp

do_pp(arg: str) -> None

Rich pretty-print the expanded value of an expression (pp <expr>).

Args: arg (str): Expression string to evaluate and pretty-print.

Source code in src/debug_dojo/_core/debugger/debugger.py
@override
def do_pp(self, arg: str) -> None:
    """Rich pretty-print the expanded value of an expression (`pp <expr>`).

    Args:
        arg (str): Expression string to evaluate and pretty-print.

    """
    ok, val = self._eval_arg(arg)
    if ok:
        self._store_last_result(val)
        rich_pprint(val, console=self._console(), expand_all=True)

do_pinfo

do_pinfo(arg: str) -> None

Provide detailed information about an object in a Rich panel (pinfo).

Args: arg (str): Expression or object name to inspect.

Source code in src/debug_dojo/_core/debugger/debugger.py
@override
def do_pinfo(self, arg: str) -> None:
    """Provide detailed information about an object in a Rich panel (`pinfo`).

    Args:
        arg (str): Expression or object name to inspect.

    """
    target_expr = arg.strip()
    if not target_expr:
        rich_inspect(
            self._get_frame_locals(self.curframe),
            console=self._console(),
            title="Frame Locals",
        )
        return
    ok, val = self._eval_arg(target_expr)
    if ok:
        rich_inspect(
            val,
            console=self._console(),
            methods=True,
            title=target_expr,
        )

do_pinfo2

do_pinfo2(arg: str) -> None

Provide extra detailed information about an object (pinfo2).

Args: arg (str): Expression or object name to inspect in full detail.

Source code in src/debug_dojo/_core/debugger/debugger.py
@override
def do_pinfo2(self, arg: str) -> None:
    """Provide extra detailed information about an object (`pinfo2`).

    Args:
        arg (str): Expression or object name to inspect in full detail.

    """
    target_expr = arg.strip()
    if not target_expr:
        rich_inspect(
            self._get_frame_locals(self.curframe),
            console=self._console(),
            all=True,
            title="Frame Locals",
        )
        return
    ok, val = self._eval_arg(target_expr)
    if ok:
        rich_inspect(
            val,
            console=self._console(),
            methods=True,
            all=True,
            title=target_expr,
        )

do_args

do_args(arg: str) -> None

Display the argument list of the current function in a Rich table (a).

Args: arg (str): Unused command argument string.

Source code in src/debug_dojo/_core/debugger/debugger.py
@override
def do_args(self, arg: str) -> None:
    """Display the argument list of the current function in a Rich table (`a`).

    Args:
        arg (str): Unused command argument string.

    """
    del arg
    frame = getattr(self, "curframe", None)
    if frame is None:
        self.error("No active frame.")
        return
    frame_locals = self._get_frame_locals(frame)
    arg_names = _extract_arg_names(frame.f_code)
    console = self._console()
    if not arg_names:
        console.print("[dim]No function arguments in current frame.[/dim]")
        return
    items = [
        (name, frame_locals.get(name), name in frame_locals) for name in arg_names
    ]
    console.print(_build_variables_table("Function Arguments", items))

do_interact

do_interact(arg: str) -> None

Start an interactive IPython shell in the current frame (interact).

Args: arg (str): Unused command argument string.

Source code in src/debug_dojo/_core/debugger/debugger.py
@override
def do_interact(self, arg: str) -> None:
    """Start an interactive IPython shell in the current frame (`interact`).

    Args:
        arg (str): Unused command argument string.

    """
    del arg
    frame = getattr(self, "curframe", None)
    if frame is None:
        self.error("No active frame.")
        return
    ns: dict[str, Any] = {
        **frame.f_globals,
        **self._get_frame_locals(frame),
    }
    self._console().print(
        "[bold cyan]Interactive IPython shell "
        "[dim](Ctrl-D or exit() to return to dpdb)[/dim][/bold cyan]"
    )
    embed_shell = InteractiveShellEmbed(banner1="", exit_msg="")  # ruff: ignore[debugger] -- do_interact intentionally instantiates an embedded IPython shell
    embed_shell(local_ns=ns, global_ns=frame.f_globals)
    frame_locals = cast(
        "MutableMapping[str, object]", self._get_frame_locals(frame)
    )
    for k, v in ns.items():
        if k not in frame.f_globals and not k.startswith("_ih"):
            frame_locals[k] = v

do_help

do_help(arg: str = '') -> bool | None

Display the categorized command reference table or help for a command (h).

Args: arg (str): Optional command or topic name.

Returns: bool | None: Superclass return value when delegating to topic handlers.

Source code in src/debug_dojo/_core/debugger/debugger.py
@override
def do_help(self, arg: str = "") -> bool | None:
    """Display the categorized command reference table or help for a command (`h`).

    Args:
        arg (str): Optional command or topic name.

    Returns:
        bool | None: Superclass return value when delegating to topic handlers.

    """
    target = arg.strip()
    console = self._console()
    if not target:
        console.print(_build_help_table())
        return None
    if hasattr(self, f"help_{target}"):
        return super().do_help(target)
    cmd_fn = getattr(self, f"do_{target}", None)
    if cmd_fn is None:
        self.error(f"No help for {target!r}")
        return None
    doc = getattr(cmd_fn, "__doc__", None)
    if not isinstance(doc, str) or not doc.strip():
        self.error(f"No help for {target!r}; docstring missing")
        return None
    console.print(_build_command_help_panel(target, doc))
    return None

debug_dojo._core.debugger.breakpoints

Breakpoint management, AST symbol lookup, and callable target resolution.

Functions:

Name Description
has_active_breakpoints

Return whether any bdb.Breakpoint is currently registered.

has_active_breakpoints

has_active_breakpoints() -> bool

Return whether any bdb.Breakpoint is currently registered.

Returns: bool: True when at least one active breakpoint exists in bdb.

Source code in src/debug_dojo/_core/debugger/breakpoints.py
def has_active_breakpoints() -> bool:
    """Return whether any `bdb.Breakpoint` is currently registered.

    Returns:
        bool: `True` when at least one active breakpoint exists in `bdb`.

    """
    return any(bp is not None for bp in bdb.Breakpoint.bpbynumber)

debug_dojo._core.debugger.session

Session lifecycle, excepthook handling, and debugger entrypoint functions.

Functions:

Name Description
wrap_sys_excepthook

Wrap sys.excepthook with _bdb_quit_excepthook once.

set_trace

Enter the internal DPDB debugger at the given or calling stack frame.

setup

Set internal DPDB as the active debugger.

post_mortem

Enter post-mortem debugging on the given or active exception traceback.

pm

Enter dpdb post-mortem debugging on the last unhandled exception.

seed_cli_breakpoints

Register CLI-supplied breakpoints before target execution.

run_with_active_breakpoints

Execute call under dpdb trace dispatch so active breakpoints fire.

wrap_sys_excepthook

wrap_sys_excepthook() -> None

Wrap sys.excepthook with _bdb_quit_excepthook once.

Source code in src/debug_dojo/_core/debugger/session.py
def wrap_sys_excepthook() -> None:
    """Wrap `sys.excepthook` with `_bdb_quit_excepthook` once."""
    if sys.excepthook is not _bdb_quit_excepthook:
        _bdb_quit_excepthook.excepthook_ori = sys.excepthook  # pyrefly: ignore[missing-attribute]
        sys.excepthook = _bdb_quit_excepthook

set_trace

set_trace(frame: FrameType | None = None) -> None

Enter the internal DPDB debugger at the given or calling stack frame.

Args: frame (FrameType | None): Target stack frame. Defaults to the caller's frame.

Source code in src/debug_dojo/_core/debugger/session.py
def set_trace(frame: FrameType | None = None) -> None:
    """Enter the internal DPDB debugger at the given or calling stack frame.

    Args:
        frame (FrameType | None): Target stack frame. Defaults to the caller's frame.

    """
    wrap_sys_excepthook()
    target_frame = (
        sys._getframe().f_back  # ruff: ignore[private-member-access] -- sys._getframe is required to resolve the caller stack frame
        if frame is None
        else frame
    )
    pdb_instance = _init_pdb()
    shell = getattr(pdb_instance, "shell", None)
    if shell is not None and hasattr(shell, "restore_sys_module_state"):
        shell.restore_sys_module_state()
    pdb_instance.set_trace(target_frame)

setup

setup() -> None

Set internal DPDB as the active debugger.

Source code in src/debug_dojo/_core/debugger/session.py
def setup() -> None:
    """Set internal DPDB as the active debugger."""
    wrap_sys_excepthook()
    os.environ[BREAKPOINT_ENV_VAR] = DPDB_SET_TRACE_HOOK
    sys.breakpointhook = cast("Any", set_trace)

post_mortem

post_mortem(tb: TracebackType | None = None) -> None

Enter post-mortem debugging on the given or active exception traceback.

Args: tb (TracebackType | None): Traceback to inspect (defaults to active exc_info).

Source code in src/debug_dojo/_core/debugger/session.py
def post_mortem(tb: TracebackType | None = None) -> None:
    """Enter post-mortem debugging on the given or active exception traceback.

    Args:
        tb (TracebackType | None): Traceback to inspect (defaults to active exc_info).

    """
    wrap_sys_excepthook()
    pdb_instance = _init_pdb()
    pdb_instance.reset()
    target_tb = sys.exc_info()[2] if tb is None else tb
    if target_tb is not None:
        console = (
            pdb_instance._console()  # ruff: ignore[private-member-access] -- _console is internal to DojoPdb in this package
            if isinstance(pdb_instance, DojoPdb)
            else Console(file=getattr(pdb_instance, "stdout", sys.stdout))
        )
        _render_post_mortem_banner(target_tb, console)
        pdb_instance.interaction(None, target_tb)

pm

pm() -> None

Enter dpdb post-mortem debugging on the last unhandled exception.

Source code in src/debug_dojo/_core/debugger/session.py
def pm() -> None:
    """Enter `dpdb` post-mortem debugging on the last unhandled exception."""
    last_exc = getattr(sys, "last_exc", None)
    tb = (
        last_exc.__traceback__
        if isinstance(last_exc, BaseException)
        else getattr(sys, "last_traceback", None)
    )
    post_mortem(tb)

seed_cli_breakpoints

seed_cli_breakpoints(target_file: str, breaks: Sequence[str]) -> None

Register CLI-supplied breakpoints before target execution.

Args: target_file (str): Path to the resolved target script. breaks (Sequence[str]): Breakpoint specifications (line, file:line, func).

Source code in src/debug_dojo/_core/debugger/session.py
def seed_cli_breakpoints(target_file: str, breaks: Sequence[str]) -> None:
    """Register CLI-supplied breakpoints before target execution.

    Args:
        target_file (str): Path to the resolved target script.
        breaks (Sequence[str]): Breakpoint specifications (`line`, `file:line`, `func`).

    """
    pdb_instance = _init_pdb()
    resolved_default = str(Path(target_file).resolve())
    for spec in breaks:
        _apply_break_spec(pdb_instance, resolved_default, spec)

run_with_active_breakpoints

run_with_active_breakpoints(call: Callable[[], object]) -> None

Execute call under dpdb trace dispatch so active breakpoints fire.

Args: call (Callable[[], object]): Zero-argument callable executing the target.

Source code in src/debug_dojo/_core/debugger/session.py
def run_with_active_breakpoints(call: Callable[[], object]) -> None:
    """Execute `call` under `dpdb` trace dispatch so active breakpoints fire.

    Args:
        call (Callable[[], object]): Zero-argument callable executing the target.

    """
    wrap_sys_excepthook()
    pdb_instance = _init_pdb()
    shell = getattr(pdb_instance, "shell", None)
    if shell is not None and hasattr(shell, "restore_sys_module_state"):
        shell.restore_sys_module_state()
    pdb_instance.reset()
    caller_frame = sys._getframe()  # ruff: ignore[private-member-access] -- anchor botframe to runner frame
    pdb_instance.botframe = caller_frame
    pdb_instance.set_continue()
    prev_trace = sys.gettrace()
    sys.settrace(pdb_instance.trace_dispatch)
    try:
        _ = call()
    finally:
        pdb_instance.quitting = True
        sys.settrace(prev_trace)

debug_dojo._core.debugger.views

Visual formatting, Rich tables, and inspection panels for dpdb.

Functions:

Name Description
is_runner_frame

Return whether frame belongs to an internal runner or CLI framework module.

is_runner_frame

is_runner_frame(frame: FrameType) -> bool

Return whether frame belongs to an internal runner or CLI framework module.

Args: frame (FrameType): Stack frame to inspect.

Returns: bool: True if the frame belongs to debug_dojo, runpy, bdb, typer, or click.

Source code in src/debug_dojo/_core/debugger/views.py
def is_runner_frame(frame: FrameType) -> bool:
    """Return whether `frame` belongs to an internal runner or CLI framework module.

    Args:
        frame (FrameType): Stack frame to inspect.

    Returns:
        bool: `True` if the frame belongs to `debug_dojo`, `runpy`, `bdb`, `typer`,
            or `click`.

    """
    filename = frame.f_code.co_filename
    if filename == "<frozen runpy>" or Path(filename).name in {"dojo", "debug-dojo"}:
        return True
    mod_name = str(frame.f_globals.get("__name__", ""))
    return any(
        mod_name == prefix or mod_name.startswith(f"{prefix}.")
        for prefix in _HIDDEN_MODULE_PREFIXES
    )

Installer Subsystem

debug_dojo._core.installers

Module for installing opinionated debugging tools into Python's builtins.

Functions:

Name Description
install_tools

Configure dpdb and inject b, p, i, and c into builtins.

install_tools

install_tools() -> None

Configure dpdb and inject b, p, i, and c into builtins.

install_tools() import builtins all(callable(getattr(builtins, name)) for name in ("b", "p", "i", "c")) True

Source code in src/debug_dojo/_core/installers.py
def install_tools() -> None:
    """Configure `dpdb` and inject `b`, `p`, `i`, and `c` into `builtins`.

    >>> install_tools()
    >>> import builtins
    >>> all(callable(getattr(builtins, name)) for name in ("b", "p", "i", "c"))
    True

    """
    setup()
    _ = traceback.install(show_locals=False)
    builtins.__dict__["b"] = breakpoint
    builtins.__dict__["p"] = rich_print
    builtins.__dict__["i"] = _inspect_with_defaults
    builtins.__dict__["c"] = inspect_objects_side_by_side

Execution Subsystem

debug_dojo._core.execution

Module for executing targets with debugging tools.

Functions:

Name Description
execute_with_debug

Execute a target script, module, or command with dpdb and debugging tools.

execute_with_debug

execute_with_debug(
    target_name: str, target_args: list[str], *, breaks: Sequence[str] | None = None
) -> None

Execute a target script, module, or command with dpdb and debugging tools.

Args: target_name (str): The name of the script, module, or executable to run. target_args (list[str]): Arguments to pass to the target. breaks (Sequence[str] | None): Optional CLI breakpoint specifications.

Source code in src/debug_dojo/_core/execution.py
def execute_with_debug(
    target_name: str,
    target_args: list[str],
    *,
    breaks: Sequence[str] | None = None,
) -> None:
    """Execute a target script, module, or command with `dpdb` and debugging tools.

    Args:
        target_name (str): The name of the script, module, or executable to run.
        target_args (list[str]): Arguments to pass to the target.
        breaks (Sequence[str] | None): Optional CLI breakpoint specifications.

    """
    _configure_sys_argv(target_name, target_args)
    _configure_project_venv(target_name)
    install_tools()
    runner, resolved_target = _get_runner_and_target(target_name)
    if breaks:
        seed_cli_breakpoints(resolved_target, breaks)
    _safe_execute(runner, resolved_target)

Comparison Subsystem

debug_dojo._core.compare

Utilities for side-by-side inspection and comparison of Python objects.

This module provides functions to display attributes and methods of two objects in a visually appealing, side-by-side format in the terminal.

Functions:

Name Description
get_object_attributes

Extract and format non-callable attributes of an object.

get_object_methods

Extract and format public callable methods of an object.

get_simplified_object_info

Generate a simplified, Rich-formatted inspection output for an object.

inspect_objects_side_by_side

Display two Python objects side-by-side in the terminal using Rich.

get_object_attributes

get_object_attributes(obj: object) -> list[str]

Extract and format non-callable attributes of an object.

Args: obj (object): The object to extract attributes from.

Returns: list[str]: A list of formatted strings, each representing an attribute.

Source code in src/debug_dojo/_core/compare.py
def get_object_attributes(obj: object) -> list[str]:
    """Extract and format non-callable attributes of an object.

    Args:
        obj (object): The object to extract attributes from.

    Returns:
        list[str]: A list of formatted strings, each representing an attribute.

    """
    return _get_members(
        obj,
        lambda n, v: not n.startswith("__") and not callable(v),
        lambda n, v: f"{n}={v!r}",
    )

get_object_methods

get_object_methods(obj: object) -> list[str]

Extract and format public callable methods of an object.

Args: obj (object): The object to extract methods from.

Returns: list[str]: A list of method names.

Source code in src/debug_dojo/_core/compare.py
def get_object_methods(obj: object) -> list[str]:
    """Extract and format public callable methods of an object.

    Args:
        obj (object): The object to extract methods from.

    Returns:
        list[str]: A list of method names.

    """
    return _get_members(
        obj,
        lambda n, v: not n.startswith("_") and callable(v),
        lambda n, _v: n,
    )

get_simplified_object_info

get_simplified_object_info(obj: object) -> list[Text]

Generate a simplified, Rich-formatted inspection output for an object.

Handles basic Python types by displaying their value directly. For other objects, it lists their attributes and public methods.

Args: obj (object): The object to generate info for.

Returns: list[Text]: A list of Rich Text objects representing the object's information.

Source code in src/debug_dojo/_core/compare.py
def get_simplified_object_info(obj: object) -> list[Text]:
    """Generate a simplified, Rich-formatted inspection output for an object.

    Handles basic Python types by displaying their value directly. For other objects, it
    lists their attributes and public methods.

    Args:
        obj (object): The object to generate info for.

    Returns:
        list[Text]: A list of Rich Text objects representing the object's information.

    """
    info_lines: list[Text] = []
    obj_type: str = type(obj).__name__
    info_lines.extend((Text(f"<class '{obj_type}'>", style="cyan bold"), Text("")))

    if _is_basic_type(obj):
        info_lines.extend(_get_basic_info(obj))
        return info_lines

    info_lines.extend(_get_attributes_section(obj))
    info_lines.extend(_get_methods_section(obj))

    return info_lines

inspect_objects_side_by_side

inspect_objects_side_by_side(obj1: object, obj2: object) -> None

Display two Python objects side-by-side in the terminal using Rich.

Shows attributes and methods of both objects in a simplified, aligned format.

Args: obj1 (object): The first object to display. obj2 (object): The second object to display.

Source code in src/debug_dojo/_core/compare.py
def inspect_objects_side_by_side(
    obj1: object,
    obj2: object,
) -> None:
    """Display two Python objects side-by-side in the terminal using Rich.

    Shows attributes and methods of both objects in a simplified, aligned format.

    Args:
        obj1 (object): The first object to display.
        obj2 (object): The second object to display.

    """
    main_console: Console = Console()

    # Get info for both objects
    lines1: list[Text] = get_simplified_object_info(obj1)
    lines2: list[Text] = get_simplified_object_info(obj2)

    # Convert list of Text to a single Renderable for Panel
    inspect_text1: Text = Text("\n").join(lines1)
    inspect_text2: Text = Text("\n").join(lines2)

    # Create Panels for each object's info
    panel1: Panel = Panel(inspect_text1, border_style="green", expand=True)
    panel2: Panel = Panel(inspect_text2, border_style="green", expand=True)

    # Use a Table to display panels side-by-side
    table = Table(show_header=False, show_lines=False, expand=True)
    table.add_column(width=main_console.width // 2 - 1)
    table.add_column(width=main_console.width // 2 - 1)
    table.add_row(panel1, panel2)

    main_console.print(table)