Operator precedence problem
Marko Rauhamaa
marko at pacujo.net
Mon Jun 6 10:22:56 EDT 2016
Random832 <random832 at fastmail.com>:
> Sure, it's obvious to _me_ that << and >> have higher precedence than &
> and |, and that "and" has a higher precedence than "or", but can I
> assume the other people know this?
No need to assume. Just read the spec:
lambda Lambda expression
if – else Conditional expression
or Boolean OR
and Boolean AND
not x Boolean NOT
in, not in, is, is not, <, <=, >, >=, !=, ==
Comparisons, including membership tests and identity
tests
| Bitwise OR
^ Bitwise XOR
& Bitwise AND
<<, >> Shifts
+, - Addition and subtraction
*, @, /, //, % Multiplication, matrix multiplication division,
remainder [5]
+x, -x, ~x Positive, negative, bitwise NOT
** Exponentiation [6]
await x Await expression
x[index], x[index:index], x(arguments...), x.attribute
Subscription, slicing, call, attribute reference
(expressions...), [expressions...], {key: value...}, {expressions...}
Binding or tuple display, list display, dictionary
display, set display
<URL: https://docs.python.org/3/reference/expressions.html#operat
or-precedence>
> [To keep this on-topic, let's assume that this discussion has a goal of
> getting something along the lines of "always/sometimes/never use
> "unnecessary" parentheses" into PEP7/PEP8. Speaking of, did you know
> that C has lower precedence for the bitwise operators &^| than for
> comparisons? That was something that tripped me up for a very long time
> and undermined my confidence as to other aspects of the bitwise
> operators]
Yes, I happened to know that. Python's the same way.
However, no need to memorize. It's all there in the spec. Same as with
stdlib functions. Keep checking the spec.
You *can* assume other people have read the spec. Even more importantly,
you can assume the Python interpreter complies with the spec.
Marko
More information about the Python-list
mailing list