Operator Precedence: One Thing Python Got Right

BartC bc at freeuk.com
Mon Jun 27 05:53:09 EDT 2016


On 27/06/2016 05:20, Lawrence D’Oliveiro wrote:
> There is one thing Python did not slavishly copy from C. While it has (mostly) the same operators, and exclusively adopted the iso646 names for the Boolean operators (which you can also use in C and C++, by the way, but not Java), it made a slight tweak to the operator precedence rules <https://docs.python.org/3/reference/expressions.html#operator-precedence>. Namely, whereas in C, C++ or Java you have to write
>
>     (bitval & bitmask) == needbits
>
> in Python you can dispense with the parentheses
>
>     bitval & bitmask == needbits

C has some 15 operator precedences (even if you consider only normal 
binary operators, there are 10; and that doesn't include "**").

It's not something you would choose to adopt in another language!

(On the subject of things wrong with C, here's a list I made of around 100:

https://github.com/bartg/langs/blob/master/C%20Problems.md

Although from the point of view of a more streamlined and modern 
low-level statically-typed language, not of one like Python.)

> How did I discover this? Entirely by accident: I forgot the parentheses one day and *didn’t* hit a bug. :)

That's not wise. It could have worked by chance. And putting in the 
parentheses anyway means the fragment of code stays interchangeable with C.

-- 
Bartc



More information about the Python-list mailing list