[Python-ideas] inspect.getclassdistance

Alexis Lee alexisl at hp.com
Mon Jan 5 14:44:50 CET 2015


Steven D'Aprano said on Mon, Jan 05, 2015 at 10:43:15PM +1100:
> Er, not really. What does distance mean in the context of classes? When 
> would you use this? Can you give some examples, e.g. what's the distance 
> between int and str?

Thanks for your fast response!

Distance means the number of classes in the inheritance hierarchy
between classes A and B. EG given a system:

    A <-- B1 <-- B2 <-- D
    ^                  /
     '--------C-------"

Given by:

    class A(object)
    class B1(A)
    class B2(B1)
    class C(A)
    class D(B2, C)

The distances should be:

                    dst
            A    B1   B2   C    D
        A   0    None None None None
        B1  1    0    None None None
    src B2  2    1    0    None None
        C   1    None None 0    None
        D   2    2    1    1    0

> >     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.
> >         """

Maybe the above could be inferred if this last line was changed to:

    Performs a breadth-first search for dst, either through all the
    bases of src (if a single class is given) or through the
    bases of each class given by a pair.
    Returns the minimal number of jumps required to reach a base class
    equal to dst.

> >         if type(srcs) != list:
> >             srcs = [(srcs, 0)]
> >         if len(srcs) == 0:
> >             return None
> 
> Shouldn't that be an exception?

It certainly could be. Does TypeError sound appropriate?

> >         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)
> 
> What's classDistance?

Oops - the old method name. Should be getclassdistance.


Alexis
-- 
Nova Engineer, HP Cloud.  AKA lealexis, lxsli.


More information about the Python-ideas mailing list