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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With