Create a single object from chained comparison in Python

45 Views Asked by At

I am toying around with chained comparison in Python, that is, something like a < b < c. According to the docs, it is evaluated as (a < b) and (b < c), where b is evaluated only once.

I do this to save inequalities of symbolic expressions to a list. For example:

l = Keeper()
a = Symbol()
b = Symbol()
c = Symbol()
l.add(a < b)
l.add(b < c)

This works nicely. Now I've seen in the HiGHS documentation something and am baffled how they do it. Here they give this example:

x0 = h.addVar(lb = 0, ub = 4)
x1 = h.addVar(lb = 1, ub = 7)

h.addConstr(5 <= x0 + 2*x1 <= 15)

with the implication that this means what one would expect with standard mathematic notation.

How do they do it? The best I can do is create either the 5 <= x0 + 2*x1 part or the x0 + 2*x1 <= 15, but never both.

Any ideas?

1

There are 1 best solutions below

2
On

Not really an answer, but I checked:

class C():
    def __init__(self, value):
        self.value = value

    def __and__(self, y):
        return C('(' + self.value + '&' + y.value + ')')

    def __lt__(self, y):
        return C('(' + self.value + '<' + y.value + ')')

    def __bool__(self):
        return self

a = C('1')
b = C('2')
c = C('3')
print((a < b < c).value)

and get:

TypeError: __bool__ should return bool, returned C

so maybe the library you mention somehow overrides this prohibition of __bool__ returning a bool?