how to overload operator "< <" (a < x < b)?

Carl Banks pavlovevidence at gmail.com
Sat Aug 8 06:10:35 CEST 2009


On Aug 7, 9:01 pm, Carl Banks <pavlovevide... at gmail.com> wrote:
> On Aug 7, 7:18 am, "Diez B. Roggisch" <de... at nospam.web.de> wrote:
>
>
>
>
>
> > alex23 schrieb:
>
> > > On Aug 7, 10:50 pm, Benjamin Kaplan <benjamin.kap... at case.edu> wrote:
> > >> That isn't an operator at all. Python does not support compound
> > >> comparisons like that. You have to do "a > b and b > c".
>
> > > You know, it costs nothing to open up a python interpreter and check
> > > your certainty:
>
> > >>>> x = 10
> > >>>> 1 < x < 20
> > > True
>
> > > This is a _very_ common pattern.
>
> > >>>> class X(object):
> > > ...   def __lt__(self, other):
> > > ...     print 'in lt'
> > > ...     return True
> > > ...   def __gt__(self, other):
> > > ...     print 'in gt'
> > > ...     return True
> > > ...
> > >>>> x = X()
> > >>>> 1 < x < 20
> > > in gt
> > > in lt
> > > True
> > >>>> 20 < x < 1
> > > in gt
> > > in lt
> > > True
>
> > > dmitrey: Diez' advice was the best you received.
>
> > Not really. I didn't get the chaining, and Peter is right that for that
> > there is no real overloading.
>
> You can program __lt__, __gt__, and friends to return a closure with a
> boolean value.  See my upcoming reply to the author.

Actually, scratch that.  It won't work because the chained comparison
short-circuits.  If you have __lt__ return a closure then a < b won't
work unless a < b is always true, which means it'll cause ordinary
binary comparison to fail.  Oh well.


Carl Banks



More information about the Python-list mailing list