Skip to content

Instantly share code, notes, and snippets.

@lucaswiman
Created April 12, 2022 08:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucaswiman/fbf0ac2168da7b8d358a4d1128aee230 to your computer and use it in GitHub Desktop.
Save lucaswiman/fbf0ac2168da7b8d358a4d1128aee230 to your computer and use it in GitHub Desktop.
Context manager to add a breakpoint at a particular code location
from pdb import Pdb, set_trace
from contextlib import contextmanager
@contextmanager
def debug_at(filename, lineno, condition=None):
p = Pdb()
filename = p.canonic(filename)
break_command = f"break {filename}:{lineno}" + (f', {condition}' if condition else '')
p.rcLines.append(break_command)
p.rcLines.append('continue')
try:
p.set_trace()
yield
finally:
p.clear_break(filename, lineno)
@lucaswiman
Copy link
Author

e.g.:

with debug_at("/Users/lucaswiman/.pyenv/versions/3.9.1/lib/python3.9/pathlib.py", 1076, condition="self == self"):
    pathlib.Path("Asdf")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment