compare classes and not class instances

Peter Otten __peter__ at web.de
Thu Mar 2 11:00:52 CET 2006


jantod at gmail.com wrote:

> I not only want to compare class *instances* but also the classes
> themselves. Something like:
 
> sorted([B, A]) => [A, B]
> 
> My motivation for doing so is simply to sort classes based on their
> names and not (as it seems is the default behaviour) on the order in
> which they were created.
> 
> I guess I could always just do something like sorted(classes,
> key=lambda cls: cls.__name__)...but where's the fun in that? :-)

A class is just an instance of its metaclass. Therefore the metaclass is the
right place to implement the __cmp__() method:

>>> class T:
...     class __metaclass__(type):
...             def __cmp__(cls, other):
...                     return cmp(cls.__name__, other.__name__)
...
>>> class B(T): pass
...
>>> class A(T): pass
...
>>> class C(T): pass
...
>>> sorted([C, B, A])
[<class '__main__.A'>, <class '__main__.B'>, <class '__main__.C'>]

Peter



More information about the Python-list mailing list