Sort by an object's type
Posted
by Richard Levasseur
on Stack Overflow
See other posts from Stack Overflow
or by Richard Levasseur
Published on 2010-05-28T03:41:44Z
Indexed on
2010/05/28
3:51 UTC
Read the original article
Hit count: 342
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.
© Stack Overflow or respective owner