Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to overload the multiple comparison syntax in python?

Tags:

python

I'm wondering if it's possible to overload the multiple comparison syntax in python:

a < b < c

I know it's possible to overload single comparisons, is it possible to overload these?

like image 829
Joe Doliner Avatar asked Jun 19 '13 17:06

Joe Doliner


1 Answers

Internally it is handled as a < b and b < c, so you need to overload only __lt__, __gt__, etc.

From the docs:

x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

>>> import dis
>>> dis.dis(lambda : a < b < c)
  1           0 LOAD_GLOBAL              0 (a)
              3 LOAD_GLOBAL              1 (b)
              6 DUP_TOP             
              7 ROT_THREE           
              8 COMPARE_OP               0 (<)
             11 JUMP_IF_FALSE_OR_POP    21
             14 LOAD_GLOBAL              2 (c)
             17 COMPARE_OP               0 (<)
             20 RETURN_VALUE        
        >>   21 ROT_TWO             
             22 POP_TOP             
             23 RETURN_VALUE  

Demo:

class A(object):
    def __lt__(self, other):
        print 'inside lt'
        return True
    def __gt__(self, other):
        print 'inside gt'
        return True
...        
>>> a = A()
>>> 10 < a < 20
inside gt
inside lt
True
like image 164
Ashwini Chaudhary Avatar answered Nov 03 '22 13:11

Ashwini Chaudhary