Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>For a full set of comparison functions I have used the following mixin, which you could put in say for example a mixin.py in your module.</p> <pre><code>class ComparableMixin(object): def _compare(self, other, method): try: return method(self._cmpkey(), other._cmpkey()) except (AttributeError, TypeError): # _cmpkey not implemented, or return different type, # so I can't compare with "other". return NotImplemented def __lt__(self, other): return self._compare(other, lambda s, o: s &lt; o) def __le__(self, other): return self._compare(other, lambda s, o: s &lt;= o) def __eq__(self, other): return self._compare(other, lambda s, o: s == o) def __ge__(self, other): return self._compare(other, lambda s, o: s &gt;= o) def __gt__(self, other): return self._compare(other, lambda s, o: s &gt; o) def __ne__(self, other): return self._compare(other, lambda s, o: s != o) </code></pre> <p>To use the mixin above you need to implement a _cmpkey() method that returns a key of objects that can be compared, similar to the key() function used when sorting. The implementation could look like this:</p> <pre><code>&gt;&gt;&gt; from .mixin import ComparableMixin &gt;&gt;&gt; class Orderable(ComparableMixin): ... ... def __init__(self, firstname, lastname): ... self.first = firstname ... self.last = lastname ... ... def _cmpkey(self): ... return (self.last, self.first) ... ... def __repr__(self): ... return "%s %s" % (self.first, self.last) ... &gt;&gt;&gt; sorted([Orderable('Donald', 'Duck'), ... Orderable('Paul', 'Anka')]) [Paul Anka, Donald Duck] </code></pre> <p>The reason I use this instead of the total_ordering recipe is <a href="http://bugs.python.org/issue10042" rel="nofollow">this bug</a>. It's fixed in Python 3.4, but often you need to support older Python versions as well.</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.
    3. 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