Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you want to know if an object is <strong>sortable</strong>, you must check if it implements the necessary methods of comparison.</p> <p>In <strong>Python 2.X</strong> there were two different ways to implement those methods:</p> <ol> <li><p>cmp method (equivalent of compareTo in Java per example)</p> <p><code>__cmp__(self, other)</code>: returns >0, 0 or &lt;0 wether self is more, equal or less than <em>other</em></p></li> <li><p>rich comparison methods</p> <p><code>__lt__, __gt__, __eq__, __le__, __ge__, __ne__</code></p> <p>The sort() functions call this method to make the necessary comparisons between instances (actually sort only needs the <code>__lt__</code> or <code>__gt__</code> methods but it's recommended to implement all of them)</p></li> </ol> <p>In <strong>Python 3.X</strong> the <code>__cmp__</code> was removed in favor of the rich comparison methods as having more than one way to do the same thing is really against Python's "laws".</p> <p>So, you basically need a function that check if these methods are implemented by a class:</p> <pre><code># Python 2.X def is_sortable(obj): return hasattr(obj, "__cmp__") or \ hasattr(obj, "__lt__") or \ hasattr(obj, "__gt__") # Python 3.X def is_sortable(obj): cls = obj.__class__ return cls.__lt__ != object.__lt__ or \ cls.__gt__ != object.__gt__ </code></pre> <p>Different functions are needed for Python 2 and 3 because a lot of other things also change about unbound methods, method-wrappers and other internal things in Python 3.</p> <p>Read this links you want better understanding of the sortable objects in Python:</p> <ul> <li><p><a href="http://python3porting.com/problems.html#unorderable-types-cmp-and-cmp" rel="nofollow">http://python3porting.com/problems.html#unorderable-types-cmp-and-cmp</a></p></li> <li><p><a href="http://docs.python.org/2/howto/sorting.html#the-old-way-using-the-cmp-parameter" rel="nofollow">http://docs.python.org/2/howto/sorting.html#the-old-way-using-the-cmp-parameter</a></p></li> </ul> <p>PS: this was a complete re-edit of my first answer, but it was needed as I investigated the problem better and had a cleaner idea about it :)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload