user3852791
user3852791

Reputation: 327

How do I define custom comparison (0 < mytype) in python?

So I'm currently (ab)using python notation to create a domain specific language. As part of this I'm overriding comparison functions to return non-boolean values.

So, for (mytype1 < mytype2) and (mytype < 0) I can easily do this by defining the __lt__() magic method.

However, I cannot figure out how to do so for (0 < mytype) as presumably the magic method would need to be defined on the built-in int type. There doesn't seem to be a __rlt__() function as exists for numeric operations.

How do I add support for this comparison where the lhs is of type int (in python3)?

Upvotes: 3

Views: 52

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798626

As per the documentation the reflected form of __lt__() is __gt__().

There are no swapped-argument versions of these methods (to be used when the left argument does not support the operation but the right argument does); rather, __lt__() and __gt__() are each other’s reflection, __le__() and __ge__() are each other’s reflection, and __eq__() and __ne__() are their own reflection. If the operands are of different types, and right operand’s type is a direct or indirect subclass of the left operand’s type, the reflected method of the right operand has priority, otherwise the left operand’s method has priority. Virtual subclassing is not considered.

Upvotes: 4

Related Questions