[Python-ideas] inspect.getclassdistance

Chris Angelico rosuav at gmail.com
Mon Jan 5 12:51:33 CET 2015

On Mon, Jan 5, 2015 at 10:20 PM, Alexis Lee <alexisl at hp.com> wrote:
>     def getclassdistance(srcs, dst):
>         """srcs may be either a single class or a list of (class, distance) pairs.
>         dst is the superclass to find.
>         Performs a breadth-first search for dst, returning the shortest distance.
>         """
>         if type(srcs) != list:
>             srcs = [(srcs, 0)]
>         if len(srcs) == 0:
>             return None
>         here, distance = srcs[0]
>         if here == dst:
>             return distance
>         newSrc = srcs[1:] + [(c, distance + 1) for c in list(here.__bases__)]
>         return classDistance(newSrc, dst)

I'm not 100% sure that I understand what this is doing, so here's a
reimplementation of what I think it's doing. Tell me where this one's
wrong, and you'll be a long way toward explaining what yours is
accomplishing :)

def getclassdistance(src, dst):
    """Measure the shortest parent chain which leads from src to dst

    Returns the length of the shortest such chain, or None if no chain
    srcs = [(src, 0)]
    while srcs:
        here, distance = srcs.pop(0)
        if here is dst:
            return distance
        for c in here.__bases__:
            srcs.append((c, distance+1))

I'm still not sure what the value of this is, and therefore why it
shouldn't just be a personal utility function (not everything needs to
be in the stdlib), but if this is an iterative equivalent to your
recursive function (assuming that classDistance is getclassdistance),
then it's at least reasonably simple. I made a couple of other changes
along the way, including requiring that the first arg be a single
class (is there any reason, other than recursion, to provide a
pre-populated list?), and using 'is' rather than '==' to compare
classes. But since I can't test this against your use-case, I can't
verify that it's doing the right job.


More information about the Python-ideas mailing list