Search code examples
pythondebuggingpython-idle

python IDLE debugger self variable


Is there some way to monitor self.{name} while debugging without the extra line below and also does someone has idea (good practice) how to omit the self. part in the code (after line 4 in the body of the other methods), it will make it more readable?

class QuickFindUf(object):

    def __init__(self, n):
        self._id = []

        for i in xrange(n):
            self._id.append(i)

    def connected(self, p, q):
        return self._id[p] == self._id[q]

    def union(self, p, q):
        pid = self._id[p]
        qid = self._id[q]

        l = self._id # debug only

        for i in xrange(len(self._id)):
            if self._id[i] == pid: 
                self._id[i] = qid

Solution

  • Since n in needed later, save it. As far as I can see, __init__ sets self._id to range(n) (list(range(10) in 3.x), so the rest can be condensed.

    def __init__(self, n):
        self.n = n
        self._id = range(n)  # list(range(n)) in 3.x.
    

    In any case, looking up an attribute of self just once in a method, as in l = self._id and using the direct reverence, here l, thereafter, is standard practice, not a workaround or debug-only thing. I would write union as follows:

    def union(self, p, q):
        l = self._id
        pid = l[p]
        qid = l[q]
        for i in xrange(n):
            if l[i] == pid: 
                l[i] = qid
    

    You might consider what to do if p or q are out of range. Do you have some other question?