Slide 1

Slide 1 text

Let’s create a Python Debugger together Johannes Bechberger mostlynerdless.de

Slide 2

Slide 2 text

No content

Slide 3

Slide 3 text

If debugging is the process of removing software bugs, then programming must be the process of putting them in. — Edsger Dijkstra “

Slide 4

Slide 4 text

➜ python3 counter.py \ lines counter.py 0

Slide 5

Slide 5 text

➜ python3 counter.py \ lines counter.py 26

Slide 6

Slide 6 text

Let’s look at the code

Slide 7

Slide 7 text

def main(): match cmd !:= sys.argv[1]: case "lines": count = count_code_lines(Path(sys.argv[2])) print(count) case "help": print_help() case _: raise ValueError(f"Unknown operation {cmd}")

Slide 8

Slide 8 text

def is_code_line(line: str) -> bool: return line.isspace() and line.strip().startswith("#") def count_code_lines(file: Path) -> int: count = 0 with file.open('r') as f: for line in f: if is_code_line(line): count += 1 return count

Slide 9

Slide 9 text

Any ideas?

Slide 10

Slide 10 text

Debuggers are your friend

Slide 11

Slide 11 text

Who of you used a debugger before?

Slide 12

Slide 12 text

Why debug? •Find and fix bugs! •Analyze the code •Add more logging on the fly •Change behavior on the fly •Analyze memory issues •And much more — Egor Ushakov “

Slide 13

Slide 13 text

No content

Slide 14

Slide 14 text

No content

Slide 15

Slide 15 text

We could use an existing debugger...

Slide 16

Slide 16 text

Debuggers are no rocket science, so ...

Slide 17

Slide 17 text

No content

Slide 18

Slide 18 text

https://github.com/parttimenerd/python-dbg/

Slide 19

Slide 19 text

Java has built-in debugging support...

Slide 20

Slide 20 text

But Python?

Slide 21

Slide 21 text

No content

Slide 22

Slide 22 text

Does the interpreter "know" breakpoints?

Slide 23

Slide 23 text

No.

Slide 24

Slide 24 text

Any ideas?

Slide 25

Slide 25 text

def is_code_line(line: str) -> bool: return line.isspace() and line.strip().startswith("# def count_code_lines(file: Path) -> int: count = 0 with file.open('r') as f: for line in f: if is_code_line(line): count += 1 return count dbg(); dbg(); dbg(); dbg(); dbg(); dbg(); dbg();

Slide 26

Slide 26 text

def dbg(): if at_breakpoint(file, line): dbg_shell() ? dbg(); line

Slide 27

Slide 27 text

sys._getframe

Slide 28

Slide 28 text

sys._getframe

Slide 29

Slide 29 text

sys._getframe CPython implementation detail locals(), globals(), sys._getframe(), sys.exc_info(), and sys.settrace work in PyPy, but they incur a performance penalty that can be huge by disabling the JIT over the enclosing JIT scope. “ – https://www.pypy.org/performance.html

Slide 30

Slide 30 text

main count_code_lines is_code_line dbg sys._getframe(0) sys._getframe(1) …

Slide 31

Slide 31 text

main count_code_lines is_code_line dbg sys._getframe(0) sys._getframe(1) f_back f_lineno 6 f_globals !!... f_locals {'line': 'import sys\n'} f_code. co_filename counter.py

Slide 32

Slide 32 text

def dbg(): frame = sys._getframe(1) line = frame.f_lineno file = Path(frame.f_code.co_filename).stem if at_breakpoint(file, line): dbg_shell() dbg(); line

Slide 33

Slide 33 text

def dbg(): frame = sys._getframe(1) line = frame.f_lineno file = Path(frame.f_code.co_filename).stem if at_breakpoint(file, line): dbg_shell(frame) dbg(); line

Slide 34

Slide 34 text

def dbg(): frame = sys._getframe(1) line = frame.f_lineno file = Path(frame.f_code.co_filename).stem if at_breakpoint(file, line): dbg_shell(frame) dbg(); line

Slide 35

Slide 35 text

def dbg(): frame = sys._getframe(1) line = frame.f_lineno file = Path(frame.f_code.co_filename).stem if at_breakpoint(file, line): dbg_shell(frame) def at_breakpoint(file: str, line: int) -> bool: return file !== "counter" and line !== 6 dbg(); line

Slide 36

Slide 36 text

Demo: counter0.py

Slide 37

Slide 37 text

But how do we automate this?

Slide 38

Slide 38 text

The pre-3.12 way

Slide 39

Slide 39 text

sys.settrace

Slide 40

Slide 40 text

sys.settrace(handler) Event = Union['call', 'line', 'return', 'exception', 'opcode'] def handler(frame: FrameType, event: Event, arg): pass

Slide 41

Slide 41 text

def is_code_line(line: str) -> bool: return line.isspace() and line.strip().startswith("#") def count_code_lines(file: Path) -> int: count = 0 with file.open('r') as f: for line in f: if is_code_line(line): count += 1 return count handler(frame, 'call', None) handler(frame, 'call', None)

Slide 42

Slide 42 text

Demo settrace1.py event: call main event: call count_code_lines event: call is_code_line event: call is_code_line event: call is_code_line event: call is_code_line !!...

Slide 43

Slide 43 text

sys.settrace(handler) def inner_handler(frame: FrameType, event: str, arg): pass def handler(frame: FrameType, event: Event, arg) \ -> Optional[Callable[[FrameType, Event, Any], None]]: return inner_handler

Slide 44

Slide 44 text

sys.settrace(handler) def inner_handler(frame: FrameType, event: Event, arg): pass def handler(frame: FrameType, event: Event, arg) \ -> Optional[Callable[[FrameType, Event, Any], None]]: return inner_handler

Slide 45

Slide 45 text

Demo settrace2.py event: call is_code_line inner: line 6 inner: return 6 inner: line 12 inner: line 13 !!...

Slide 46

Slide 46 text

def dbg(): frame = sys._getframe(1) line = frame.f_lineno file = Path(frame.f_code.co_filename).stem if at_breakpoint(file, line): dbg_shell(frame) def at_breakpoint(file: str, line: int) -> bool: return file !== "counter" and line !== 6 dbg(); line

Slide 47

Slide 47 text

def inner_handler(frame: FrameType, event: str, arg): if event !!= 'line': return line = frame.f_lineno file = Path(frame.f_code.co_filename).stem if at_breakpoint(file, line): dbg_shell(frame) def at_breakpoint(file: str, line: int) -> bool: return file !== "counter" and line !== 6 dbg(); line

Slide 48

Slide 48 text

def inner_handler(frame: FrameType, event: str, arg): if event !!= 'line': return line = frame.f_lineno file = Path(frame.f_code.co_filename).stem if at_breakpoint(file, line): dbg_shell(frame) def at_breakpoint(file: str, line: int) -> bool: return file !== "counter" and line !== 6 dbg(); line

Slide 49

Slide 49 text

Demo settrace3.py event: call main event: call count_code_lines event: call is_code_line in break point at line 6 !!>>> line 'import sys\n'

Slide 50

Slide 50 text

def inner_handler(frame: FrameType, event: str, arg): if event !!= 'line': return line = frame.f_lineno file = Path(frame.f_code.co_filename).stem if at_breakpoint(file, line): dbg_shell(frame) def at_breakpoint(file: str, line: int) -> bool: return file !== "counter" and line !== 6 dbg(); line make configurable first_line or Breakpoint(file, line) in current_breakpoints

Slide 51

Slide 51 text

Demo settrace4.py event: call main in break point at line 23 !!>>> br('counter', 6) !!>>> event: call count_code_lines event: call is_code_line in break point at line 6 !!>>> line 'import sys\n'

Slide 52

Slide 52 text

Single Stepping

Slide 53

Slide 53 text

main:25 count_code_lines:13 is_code_line:6 main:25 count_code_lines:12 step out Just extend at_breakpoint

Slide 54

Slide 54 text

main:25 count_code_lines:12 main:25 count_code_lines:13 step Just extend at_breakpoint

Slide 55

Slide 55 text

main:25 count_code_lines:12 main:25 count_code_lines:13 step into is_code_line:6 Just extend at_breakpoint

Slide 56

Slide 56 text

Do we get line events for every function?

Slide 57

Slide 57 text

def is_code_line(line: str) -> bool: return line.isspace() and line.strip().startswith("#") def count_code_lines(file: Path) -> int: count = 0 with file.open('r') as f: for line in f: if is_code_line(line): count += 1 return count handler(frame, …, None) add breakpoint handler(frame, 'call', None)

Slide 58

Slide 58 text

Problems?

Slide 59

Slide 59 text

Performance?

Slide 60

Slide 60 text

Any ideas to improve it?

Slide 61

Slide 61 text

Make at_breakpoint faster

Slide 62

Slide 62 text

Add a new API Python 3.12 and PEP 669

Slide 63

Slide 63 text

No content

Slide 64

Slide 64 text

# some aliases and constants mon = sys.monitoring E = mon.events TOOL_ID = mon.DEBUGGER_ID # register the tool mon.use_tool_id(TOOL_ID, "dbg")

Slide 65

Slide 65 text

# some aliases and constants mon = sys.monitoring E = mon.events TOOL_ID = mon.DEBUGGER_ID # register the tool mon.use_tool_id(TOOL_ID, "dbg") # register callbacks for the events we are interested in mon.register_callback(TOOL_ID, E.LINE, line_handler) mon.register_callback(TOOL_ID, E.PY_START, start_handler) def start_handler(code: CodeType, offset: int): pass def line_handler(code: CodeType, line: int) -> DISABLE|Any: pass disable till mon.restart_even Register Tool Register Callbacks Enable PY_START events

Slide 66

Slide 66 text

# some aliases and constants mon = sys.monitoring E = mon.events TOOL_ID = mon.DEBUGGER_ID # register the tool mon.use_tool_id(TOOL_ID, "dbg") # register callbacks for the events we are interested in mon.register_callback(TOOL_ID, E.LINE, line_handler) mon.register_callback(TOOL_ID, E.PY_START, start_handler) def start_handler(code: CodeType, offset: int): pass def line_handler(code: CodeType, line: int) -> DISABLE|Any: pass disable till mon.restart_events()

Slide 67

Slide 67 text

# some aliases and constants mon = sys.monitoring E = mon.events TOOL_ID = mon.DEBUGGER_ID # register the tool mon.use_tool_id(TOOL_ID, "dbg") # register callbacks for the events we are interested in mon.register_callback(TOOL_ID, E.LINE, line_handler) mon.register_callback(TOOL_ID, E.PY_START, start_handler) # enable PY_START event globally mon.set_events(TOOL_ID, E.PY_START) # Later mon.set_local_events(TOOL_ID, code, E.LINE) Enable LINE events in func PY_START for every func run program has breakpoint? LINE for every line run function emitted per thread, not per interpreter

Slide 68

Slide 68 text

The biggest opportunity of PEP 669 isn't even the speed, it's the fact that a debugger built on top of it will automatically support all threads. — Łukasz Langa “ https://github.com/python/cpython/issues/103103#issuecomment-1488312628

Slide 69

Slide 69 text

Globally set events Locally set events Enabled events per function

Slide 70

Slide 70 text

The power is in the fine- grained configuration

Slide 71

Slide 71 text

You can set events in f for f

Slide 72

Slide 72 text

def line_handler(code: CodeType, line_number: int): print(f" {code.co_name}: {line_number}") mon.register_callback(tool_id, E.LINE, line_handler) def f(): print("hello") mon.set_local_events(tool_id, f.!__code!__, E.LINE) print("inner") mon.set_local_events(tool_id, f.!__code!__, 0) print("end") f() # Output hello f: 18 inner f: 19 end

Slide 73

Slide 73 text

What's fast?

Slide 74

Slide 74 text

register_callback get_tool set_local_events use_tool_id set_events Fast Rather fast Slow The earlier the faster

Slide 75

Slide 75 text

Back to the debugger

Slide 76

Slide 76 text

def start_handler(code: CodeType, _: int): # !!... handle first call file = Path(code.co_filename).stem if has_breakpoint(file, code.co_firstlineno, len(list(code.co_lines()))): print(f"enable line events for {code.co_name}") enable_line_events(code) print(f"start {code.co_name}")

Slide 77

Slide 77 text

def line_handler(code: CodeType, line: int): print(f"line {line} in {code.co_name}") if at_breakpoint(code.co_name, line): print(f"in break point at line {line}") dbg_shell(sys._getframe(1))

Slide 78

Slide 78 text

Event kinds Local Events PY_START PY_RESUME PY_RETURN PY_YIELD CALL LINE INSTRUCTION JUMP BRANCH STOP_ITERATION Ancillary Events PY_START C_RAISE C_RETURN PY_YIELD CALL LINE INSTRUCTION JUMP BRANCH STOP_ITERATION Other Events PY_START PY_RAISE PY_UNWIND PY_THROW EXCEPTION_ HANDLED LINE JUMP BRANCH STOP_ITERATION controls not tied to specific location

Slide 79

Slide 79 text

Performance Hacking pyperformance for fun and profit...

Slide 80

Slide 80 text

def line_handler(*args): pass def start_handler(*args): pass mon.use_tool_id(TOOL_ID, "dbg") mon.register_callback(!!...) mon.set_events(TOOL_ID, E.PY_START) def inner_handler(*args): pass def handler(*args): return inner_handler sys.settrace(handler) sys.settrace monitoring vs vs mon.set_events(TOOL_ID, E.PY_START | E.LINE)

Slide 81

Slide 81 text

modified version: https://github.com/parttimenerd/pyperformance/tree/dbg

Slide 82

Slide 82 text

sys.settrace monitoring vs 3.5x runtime 1.2x runtime vs 2.7x runtime

Slide 83

Slide 83 text

No content

Slide 84

Slide 84 text

Is it used?

Slide 85

Slide 85 text

not yet in pdb but IDEs like PyCharm 2023.3 use it

Slide 86

Slide 86 text

“ After #103082, we will have the chance to build a much faster debugger. For breakpoints, we do not need to trigger trace function all the time and checking for the line number. [...] The bad news is - it's almost impossible to do a completely backward compatible transition because the mechanism is quite different. — Tian Gao “ https://github.com/python/cpython/issues/103103#issue-1644836791

Slide 87

Slide 87 text

Putting it all together

Slide 88

Slide 88 text

@parttimen3rd on Twitter parttimenerd on GitHub mostlynerdless.de @SweetSapMachine sapmachine.io