Skip to content

Instantly share code, notes, and snippets.

@alexmojaki
Created August 26, 2018 22:12
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 alexmojaki/08eb95f9e611d082643d8addcfc206cc to your computer and use it in GitHub Desktop.
Save alexmojaki/08eb95f9e611d082643d8addcfc206cc to your computer and use it in GitHub Desktop.
Track a value throughout a program
import sys
from bdb import Bdb
from traceback import print_stack
class Tracker(Bdb):
"""
Debugger which looks for a given value by identity in local variables of all frames
it comes across. When it finds it and the given condition function called with the value
is true, prints out a stack trace and stops tracing.
Usage example:
Tracker(x, lambda: x.y == 0).set_trace()
"""
def __init__(self, value, condition):
super().__init__()
self.condition = condition
self.value = value
def do_clear(self, arg):
pass
def user_line(self, frame):
for name, v in frame.f_locals.items():
if v is self.value:
break
else:
return
if self.condition():
print('Variable:', name, file=sys.stderr)
print_stack(f=frame)
sys.settrace(None)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment