Att Righ
Att Righ

Reputation: 1799

Run pdb whenever a variale is accessed in python?

I'm trying to debug some code that creates an error dictionary and returns it (rather than return an error as soon as something occurs).

To do this, it would be useful to track:

Is there a way of starting pdb whenever this happens.

In other language there is the concept of starting the debug whenever memory is accessed, this doesn't really apply to python.

I have found and used huntrace before for tracing. I think this could be adapted to start pdb (and there is some code for spying on variables).

I hacked up the following:

class PdbDict(Mapping):
    def __init__(self, d):
        self.d = d

    def __getitem__(self, k):
        if k == "_id":
            import pdb

            pdb.set_trace()  # XXX
        return self.d[k]

    def __setitem__(self, k, v):
        import pdb

        pdb.set_trace()  # XXX
        self.d[k] = v

    def keys(self):
        return self.d.keys()

    def values(self):
        return self.d.values()

    def items(self):
        import pdb

        pdb.set_trace()  # XXX
        return self.d.items()

    def __len__(self):
        return len(self.d)

    def __iter__(self):
        return iter(self.d.keys())

Upvotes: 0

Views: 31

Answers (0)

Related Questions