Sort by an object's type
- by Richard Levasseur
Hi all,
I have code that statically registers (type, handler_function) pairs at module load time, resulting in a dict like this:
HANDLERS = {
str: HandleStr,
int: HandleInt,
ParentClass: HandleCustomParent,
ChildClass: HandleCustomChild
}
def HandleObject(obj):
for data_type in sorted(HANDLERS.keys(), ???):
if isinstance(obj, data_type):
HANDLERS[data_type](obj)
Where ChildClass inherits from ParentClass. The problem is that, since its a dict, the order isn't defined - but how do I introspect type objects to figure out a sort key?
The resulting order should be child classes follow by super classes (most specific types first). E.g. str comes before basestring, and ChildClass comes before ParentClass. If types are unrelated, it doesn't matter where they go relative to each other.