I did not understand where is the logic in my bug, so I managed to find a minimal example. I defined one class t
, and said that something happens when you use the <= operator and that a>=b must compute b<=a.
It works fine
Then I derived a subclass u
from t
.
When I compare two values, if they are both from t
or both from u
it works as expected, but if one is from class u
and another from class t
it fails. Why ??
class t :
def __le__(self,other) : return True
def __ge__(self,other) : return(other<=self)
class u(t) :
pass
a=t()
b=u()
#works
a<=a
a>=a
b<=b
b>=b
#works
a>=b
b<=a
#doesn't work RuntimeError: maximum recursion depth exceeded
a<=b
b>=a
EDIT : There is no problem in python 2.x (from tobias_k), but I want to use python 3.3 at least
When you do a <= b
and b
is an instance of a subclass of a
's class, Python will first call b.__ge__('a')
(and then try other methods if this call returns NotImplemented
)
Here is how to implement it without infinite recursion:
>>> class t:
... def __le__(self, other):
... return True
... def __ge__(self, other):
... return NotImplemented
...
>>> class u(t):
... pass
...
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