by rjn945 · 12y ago · 0 comments
container.constrain(button.TOP == container.TOP + 50)
Python doesn't let you pass expressions! Why isn't that just getting evaluated to true or false? Is this not vanilla Python? Is there a pre-processor?I dove into the code and found the answer here[1]. button.TOP and container.TOP are both Toga Attributes, which have their equality operators redefined.
Very interesting and clever use of operator overloading.
[1] https://github.com/pybee/toga/blob/master/toga/constraint.py
Python is very good at behaving as you expect it to, despite the fact that you can implement pretty much any magic. This is down to library design more than it is language design.
prob += x*2 + y, "foo"
This sets the objective function of prob to (2x+y), and assigns it a name of "foo". prob += x*2 + y > 3, "abcd"
That puts a constraint that 2x + y > 3, called "abcd".On both of these the string is optional.
I'm also conflicted. On one hand, it's about the most compact syntax you can get for something like this - when similar libraries in languages without operator overloading resort to passing strings into functions... On the other hand, it can be utterly incomprehensible if you haven't gone through the documentation.
I see your argument about overloaded operators being dangerous for newcomers, but the syntax isn't completely fabricated.