Created
August 26, 2018 22:12
-
-
Save alexmojaki/08eb95f9e611d082643d8addcfc206cc to your computer and use it in GitHub Desktop.
Track a value throughout a program
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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