4 ms·
Python chained operators can be confusing, especially as it allows you to write things like: — x < y > z — a in b not in c WalterBright mentioned that D will g
by laurentlb 2y ago
Python chained operators can be confusing, especially as it allows you to write things like:
— x < y > z
— a in b not in c
WalterBright mentioned that D will give you an error. When designing Starlark (a derivative of Python), I also decided to give an error for this, by making the comparison operators non associative.
https://github.com/bazelbuild/starlark/blob/master/design.md#no-chained-operators https://github.com/bazelbuild/starlark/blob/master/design.md...
I agree this Python feature can look cute, but I've found it's rarely useful and can easily be avoided.
- jeroenhd 2y agoI find these expressions a lot more readable for bound checks (like `if 0 <= n < len(something):`) compared to the imperative `if (n >= 0 && n < something.length)`. This was especially true when I used it for homework, where constraints described in mathematical form were a lot more common than when dealing with real life software. The way it works in Python allows for some hilariously unreadable code, but the concept itself is good. I think it just needs more constraints to maintain readability, such as not allowing flipping the comparison sign (like in x<y>z). Banning these chained comparison operators is not necessarily a bad idea as comparison operators can easily cause confusion in that manner, but the reason they cause confusion is that many programming languages use mathematical symbols differently than actual math. A=B=C is perfectly understandable and more readable than A=B ∧ B=C. Restraining ourselves to "operand operator operand" as the only infix expression model made sense decades ago when computers had storage counted in kilobits. Today, we can let go of the limitations of yore and use mathematical expressions in a way that plain sense.
- Izkata 2y agoIf you write the bounds check in the same order it's really not that bad: (0 <= n && n < something.length)