0

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:

  • When a particular key in a dictionary is accessed and
  • When this variable is accessed.

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())
Att Righ
  • 1,439
  • 1
  • 16
  • 29
  • Why isn't if k == "_id": import pdb good enough? – maor10 Aug 09 '20 at 15:16
  • The code I'm debugging is a third party library (so not easily editable - it is editable), I don't know all the places where this is accessed, and ideally I want to track where the returned key gets used. – Att Righ Aug 09 '20 at 15:18

0 Answers0