What's the best way to find the closest matching type to an existing type?
Question: I've got a registry of classes and types in Python 2.5, like so:

    
    
    class ClassA(object):
        pass
    
    class ClassB(ClassA):
        pass 
    
    MY_TYPES = {
        basestring : 'A string',
        int : 'An integer',
        ClassA : 'This is ClassA or a subclass',
    }
    

I'd like to be able to pass types to a function, and have it look up the
closest matching type in the hierarchy. So, looking up `str` would return `"A
string"` and looking up `ClassB` would return `"This is ClassA or a subclass"`
The problem is, I don't know how to find the superclass (or, rather, trace the
MRO chain) of a type object.

What's the best way of handling this?


Answer: 
    from inspect import getmro
    [st for cls, st in MY_TYPES.items() if cls in getmro(ClassB)]
    
    ['This is ClassA or a subclass']
    

or if you're only interested in first match(es) generator version:

    
    
    (st for cls, st in MY_TYPES.iteritems() if cls in getmro(ClassB))
    

