'Iterate over ancestors of heads in the target.'

def next(self):

    if self.heads:
        ret = self.heads.pop()
        ps = self.get_parents(ret)
        self.parents[ret] = ps
        self.heads.update([p for p in ps if (p not in self.parents)])
        return ret
    return None
