Let’s create a Python Debugger together: Part 3 (Refactoring)

This is the necessary third part of my journey down the Python debugger rabbit hole; if you’re new to the series, please take a look at part 1 and part 2 first.

I promised in the last part of this series that I’ll show you how to use the new Python APIs. However, some code refactoring is necessary before I can finally proceed. The implementation in dbg.py mixes the sys.settrace related code and code that can be reused for other debugging implementations. So, this is a short blog post covering the result of the refactoring. The code can be found in dbg2.py.

Basic Data Structures

In our debugger, every breakpoint is identified by a code object, the method/scope that a breakpoint’s line is part of and a line. We don’t always have a code object for a breakpoint, so we represent the code object via the file path and the start line of the scope:

@dataclass(frozen=True)
class CodeId:
    """ Identifier of a code object (like a function) """
    path: Path
    """ File that the code object lives in """
    start_line: int
    """ Line number of the first line of the code object """

Every breakpoint also has an optional condition to support conditional breakpoints. We can call the method test to check whether the execution should stop at this breakpoint.

@dataclass(frozen=True)
class Breakpoint:
    """ Breakpoint in a code object """
    code: CodeId
    line: int
    condition: Optional[str] = None
    """ Optional conditional expression """

    def test(self, _globals: dict, _locals: dict) -> bool:
        """ Test if the execution should stop at a breakpoint """
        return self.condition is None or eval(self.condition, _globals, _locals)

There is, of course, some information we want to associate with code ids, like the code object and the set of breakpoints that belong to it. This is helpful when checking whether there are any breakpoints in a method.

@dataclass
class CodeInfo:
    """ Information about a code object """

    id: CodeId
    code: Optional[types.CodeType] = None
    """ Code object """
    breakpoints: Set[Breakpoint] = field(default_factory=set)
    """ Breakpoints in the code object """

The code objects, their mapping from code ids, and breakpoints related to a specific file are handled by the DbgFile, offering methods for accessing the code id mapping and the ability to add and remove breakpoints, and updating the code infos as necessary:

class DbgFile:
    """ Manages code objects and breakpoints for a specific file """

    def __init__(self, path: Path):
        self.path = path
        self.breakpoints: Dict[int, Breakpoint] = {}
        """ Line number -> breakpoint """
        self._codes: Dict[CodeId, CodeInfo] = {}
        """ Code id to code info, only contains code infos with breakpoints"""

    def __getitem__(self, code_id: CodeId) -> CodeInfo:
        if code_id not in self._codes:
            self._codes[code_id] = CodeInfo(code_id)
        return self._codes[code_id]

    def add_breakpoint(self, breakpoint: Breakpoint):
        self.breakpoints[breakpoint.line] = breakpoint
        code_info = self[breakpoint.code]
        code_info.breakpoints.add(breakpoint)

    def set_code_object(self, code_id: CodeId, code: types.CodeType):
        self[code_id].code = code

    def remove_breakpoint(self, breakpoint: Breakpoint):
        self.breakpoints.pop(breakpoint.line)
        self[breakpoint.code].breakpoints.remove(breakpoint)
        if len(self[breakpoint.code].breakpoints) == 0:
            self._codes.pop(breakpoint.code)

All these files are managed in turn by an instance of the FileManager class:

class FileManager:
    """ Manages code objects and breakpoints """

    def __init__(self):
        self._per_file: Dict[Path, DbgFile] = {}
        """ file -> DbgFile """
        self.codes_with_breakpoints: Set[CodeId] = set()
        """ code ids that have breakpoints """
        self.codeinfos_possibly_without_code_objects: Set[CodeId] = set()
        """ code ids that might not have code objects """

    def __getitem__(self, path: Path) -> DbgFile:
        """ Get the DbgFile for a file """
        path = path.absolute()
        if path not in self._per_file:
            self._per_file[path] = DbgFile(path)
        return self._per_file[path]

    # based on https://github.com/python/cpython/blob/17a335dd0291d09e1510157a4ebe02932ec632dd/Lib/pdb.py#L97
    @staticmethod
    def find_code(file: Path, funcname: str,
                  line: Optional[int] = None) -> Optional[CodeId]:
        """
        Find a code object location in a file with the given function name
        that contains the given line number.

        This is does use a regex to find the function definition, so it might
        not be 100% accurate.
        """
        cre = re.compile(r'def\s+%s+\s*[(]' % re.escape(funcname))
        try:
            fp = tokenize.open(file)
        except OSError:
            return None
        # consumer of this info expects the first line to be 1
        with fp:
            for lineno, line_str in enumerate(fp, start=1):
                if cre.match(line_str) and lineno <= line:
                    return CodeId(file.absolute(), lineno)
        return None

    def get_breakpoints(self, file: Path) -> Dict[int, Breakpoint]:
        """ Get all breakpoints in a file (line number -> breakpoint) """
        return self[file].breakpoints

    def set_code_object(self, code_id: CodeId, code: types.CodeType):
        self[code_id.path].set_code_object(code_id, code)
        self.codeinfos_possibly_without_code_objects.discard(code_id)

    def add_breakpoint(self, code_id: CodeId, line: int = -1,
                       condition: Optional[str] = None):
        """
        Add a breakpoint at a given line in a given code object

        line -1 is start line of function
        """
        br = Breakpoint(code_id, line, condition)
        self[code_id.path].add_breakpoint(br)
        self.codes_with_breakpoints.add(code_id)
        if self[code_id.path][code_id].code is None:
            self.codeinfos_possibly_without_code_objects.add(code_id)

    def remove_breakpoint(self, code_id: CodeId, line: int):
        """ Remove a breakpoint at a given line in a given code object """
        self[code_id.path].remove_breakpoint(Breakpoint(code_id, line))
        if len(self[code_id.path].breakpoints) == 0:
            self.codes_with_breakpoints.remove(code_id)

    def remove_breakpoints(self, file: Path) -> Set[CodeId]:
        """ Remove all breakpoints in a file and return their code ids """
        mids = set()
        for br in self.get_breakpoints(file).values():
            mids.add(br.code)
            self.remove_breakpoint(br.code, br.line)
        self._per_file.pop(file)
        return mids

    def remove_all_breakpoints(self) -> Set[CodeId]:
        """ Remove all breakpoints and return their code ids """
        self._per_file.clear()
        mids = self.codes_with_breakpoints
        self.codes_with_breakpoints = set()
        return mids

    def get_breakpoint(self, code: types.CodeType, line: int) \
            -> Optional[Breakpoint]:
        """ Get the breakpoint at a given line in a given code object """
        return self[Path(code.co_filename)].breakpoints.get(line)

    def has_breakpoints_in_code(self, code_id: CodeId) -> bool:
        """ Check if a code object has breakpoints """
        return code_id in self.codes_with_breakpoints

    def has_breakpoints_in_code_object_and_update(self, code: types.CodeType) \
            -> bool:
        """
        Check if a code object has breakpoints and set the code object if needed
        """
        id = CodeId(Path(code.co_filename).absolute(), code.co_firstlineno)
        if id in self.codeinfos_possibly_without_code_objects:
            self.set_code_object(id, code)
        return self.has_breakpoints_in_code(id)

    def get_code_info(self, code_id: CodeId) -> CodeInfo:
        return self[code_id.path][code_id]

Formatting and Shell

Our debugging shell supports code formatting and autocompletion by relying on pygments and bpython, yet it falls back to more straightforward implementations if the dependencies aren’t present. The resulting wrappers might be helpful for other projects, too; feel free to use them, but please reference this blog post as a source.

class CodeFormatter:
    """ Formats code using pygments if available """

    def __init__(self):
        # omitted for brevity, it just checks for the existence
        # of the pygments dependency and creates custom formatter
        # to be able to add line numbers and other line prefixes 

    def format(self, code: str,
               line_prefix: Callable[[int], str] = lambda i: "") -> str:
        """
        Format code using pygments if available

        :param code: the code to format
        :param line_prefix: a function that returns the prefix for a line number
        """
        if not self.uses_pygments():
            return "\n".join(
                line_prefix(i) + l for i, l in enumerate(code.splitlines()))
        return self.pygformat(self.Python3Lexer().get_tokens(code),
                              self.CustomTerminalFormatter(line_prefix))

    def print_code(self, *, code: str, current_line: int = -1,
                   breakpoints: Dict[int, Breakpoint] = None,
                   header: Optional[str] = None, start_line: int = 1,
                   end_line: int = -1, code_start_line: int = 1):
        """
        Print code on the command line

        :param code: the code to print
        :param current_line: the current line that should be highlighted,
                             -1 to not highlight anything
        :param breakpoints: breakpoints to highlight (line number -> breakpoint)
        :param header: header to print before the code
        :param start_line: the first line to print
        :param end_line: the last line to print, -1 for the last line
        :param code_start_line: the line number of the first line of the code
        """
        # omitted from brevity

    def uses_pygments(self) -> bool:
        return self.Python3Lexer is not None

Regular shells have the problem that exiting them is only possible by throwing a SystemExit exception, which typically kills the whole application. Our modified shell can interpret an instance of the ShellExit class that we pass to the SystemExit constructor, this tells the shell whether or not to exit the whole application.

@dataclass
class ShellExit:
    exit_application: bool = False
    """ exit the program? """

Besides that, we also have to extend to built-in InteractiveConsole to run every code segment with the specified set of local variables:

class CustomInteractiveConsole(InteractiveConsole):
    """ InteractiveConsole that handles SystemExit properly """

    def __init__(self, _locals: dict, filename="<console>"):
        super().__init__(_locals, filename)
        self.locals = _locals

    def runcode(self, code):
        try:
            exec(code, self.locals)
        except SystemExit:
            raise
        except:
            self.showtraceback()

Our Shell class then wraps both the bpython shell and our custom interactive console:

class Shell:
    """
    Shell for evaluating expressions, uses bpython if available,
    but falls back to the CustomInteractiveConsole
    """

    def __init__(self):
        try:
            import bpython
            self.bpython = bpython
        except ImportError:
            pass

    def _fancy_eval(self, _locals: dict, message: str):
        ret = self.bpython.embed(locals_=_locals, banner=message)
        if isinstance(ret, ShellExit):
            if ret.exit_application:
                exit()
        elif ret is not None:
            exit(ret)
        return

    def _simple_eval(self, _locals: dict, message: str):
        try:
            print(message)
            CustomInteractiveConsole(_locals).interact(banner="", exitmsg="")
        except SystemExit as e:
            if isinstance(e.args[0], ShellExit):
                if e.args[0].exit_application:
                    exit()
            else:
                exit(e.args)

    def eval(self, _locals: dict, message: str):
        """
        Run the shell, with the given locals and
        print the passed message as a banner

        Abort the shell from inside by throwing the ShellExit exception,
        set the exit_application flag to exit the program itself

        :param _locals: locals to use
        :param message: banner message
        """
        if self.bpython is not None:
            self._fancy_eval(_locals, message)
        else:
            self._simple_eval(_locals, message)

    def uses_bpython(self) -> bool:
        return self.bpython is not None
 

Stepping

Before we come to the actual debugger base class, let us shortly cover the necessary classes to facilitate single stepping:

class StepMode(Enum):
    """ Stepping mode """
    none = -1
    """ No stepping """
    over = 0
    """ Step over lines """
    into = 1
    """ Step and step into functions """
    out = 2
    """ Step out of the current function """

    @staticmethod
    def from_bools(enable: bool = True, into: bool = False,
                   out: bool = False) -> 'StepMode':
        assert not (into and out)
        if not enable:
            return StepMode.none
        return StepMode.into if into else StepMode.out if out else StepMode.over


@dataclass
class StepState:
    """ State of a currently active step """
    mode: StepMode
    frame: types.FrameType
    """ Current frame """

You can find more on single stepping and the implementation of _breakpoint in part 2 of this post series. Here, therefore, just the essential parts of the debugger base class:

class Dbg:  
    """ Debugger base class """

    def __init__(self):
        self._main_file: Optional[Path] = None
        self._in_breakpoint = False
        self._st = {}  # store between evals
        self.code_formatter = CodeFormatter()
        self.shell = Shell()
        self.manager = FileManager()
        self._is_first_call = True
        self._single_step: Optional[StepState] = None
        """ if true, step into functions when single stepping """
        self._single_step_instead_of_continue = StepMode.none
        """ 
        if not none, step instead of continue when exiting a breakpoint shell
        """

    def uses_bpython(self) -> bool:
        return self.shell.uses_bpython()

    def _breakpoint(self, frame: types.FrameType = None,
                    show_context: bool = True, reason: str = "breakpoint",
                    *args, **kwargs):
        """
        Called to offer a shell at breakpoint or after a single step
        
        Calls the _post_process method after the shell is closed with the
        list of code ids that had breakpoints added or removed.
        
        :param frame: current frame
        :param show_context: show the code context of the current location
        :param reason: reason for this invocation, e.g. "breakpoint" or "step"
        :param args: ignored args, for compatibility with sys.breakpointhook
        :param kwargs: ignored kwargs, for compatibility with sys.breakpointhook
        """
        if self._in_breakpoint:
            return

        modified_breakpoint_codes: Set[CodeId] = set()

        # omitted the code for brevity

        self._post_process(modified_breakpoint_codes)

        self._in_breakpoint = False

    def _post_process(self, modified_code_ids: Set[CodeId]):
        """
        Called after a breakpoint is evaluated

        :param modified_code_ids: code ids with added or removed breakpoints
        """
        pass

    def _process_compiled_code(self, code: types.CodeType):
        pass

    def run(self, file: Path):
        """ Run a given file with the debugger """
        self._main_file = file
        # see https://realpython.com/python-exec/#using-python-for-configuration-files
        compiled = compile(file.read_text(), filename=str(file), mode='exec')
        sys.argv.pop(0)
        sys.breakpointhook = self._breakpoint
        self._process_compiled_code(compiled)
        exec(compiled, _globals)

The nice thing with this refactoring is that all code you saw till now is not specific to the sys.settrace based debugger, a new debugger just implements its logic in the constructor and the _post_process methods and reuse all the breakpoint handling, shell implementations, and more.

Sys.settrace-based Debugger

You saw in part 1 and part 2 how we implemented our debugger using sys.settrace, but after the refactoring, the new code is slightly more readable:

class SetTraceDbg(Dbg):
    """
    sys.settrace based debugger
    """

    def __init__(self):
        super().__init__()
        sys.settrace(self._dispatch_trace)

    def _should_break_at(self, frame: types.FrameType) -> bool:
        breakpoint = self.manager.get_breakpoint(frame.f_code, frame.f_lineno)
        if breakpoint is not None:
            return breakpoint.test(frame.f_globals, frame.f_locals)
        return False

    def _handle_line(self, frame: types.FrameType):
        if self._should_break_at(frame):
            self._breakpoint(frame, reason="breakpoint")

    def _default_dispatch(self, event):
        if event == 'call':
            return self._dispatch_trace

    def _should_single_step(self, frame: types.FrameType, event) -> bool:
        if not self._single_step:
            return False
        if self._single_step.mode == StepMode.over:
            return frame == self._single_step.frame
        if self._single_step.mode == StepMode.into:
            return True
        if self._single_step.mode == StepMode.out and event == 'return':
            return frame == self._single_step.frame
        return False

    def _dispatch_trace(self, frame: types.FrameType, event, _):
        if (
                event == 'return' and frame.f_code.co_name == '<module>' and 
                frame.f_back and frame.f_back.f_code.co_filename == __file__):
            return
        if self._is_first_call and self._main_file == Path(
                frame.f_code.co_filename):
            self._is_first_call = False
            self._breakpoint(frame, show_context=False, reason="start")
            return self._default_dispatch(event)
        if self._should_single_step(frame, event):
            if event == 'return':
                if frame.f_back:
                    self._single_step.frame = frame.f_back
                    self._breakpoint(frame.f_back, reason="step")
                return
            if self._single_step.mode == StepMode.out:
                return
            if event == 'line':
                self._single_step.mode = None
                self._breakpoint(frame, reason="step")
                return
        if event == 'call':
            if self.manager.has_breakpoints_in_code_object_and_update(
                    frame.f_code) is not None:
                return self._dispatch_trace
            else:
                return self._default_dispatch(event)
        elif event == 'line':
            self._handle_line(frame)

Conclusion

Refactoring is necessary in every software project, especially if they start small and incorporate more and more features. The new version of this code allows me to reuse parts of it in different projects in the future and also allows me to implement new debuggers without modifying all the common code.

Thanks for reading. It’s not my typical Java-related content, yet I hope it was still enjoyable. I’m looking forward to publishing a new Java-related blog post and a blog post on using the new APIs from Python 3.12 soon, so stay tuned.

Leave a Reply

Your email address will not be published. Required fields are marked *