Ken
Ken

Reputation: 29

Python expression evaluation inside [ ] seems broken

Working with some internally developed tools at work I found some behavior that I can't explain. I've recreated the problem with a contrived example:

>>> _list = [3, 4]
>>> test0 = "string"
>>> test1 = 7
>>> _list[test0 == "string" & test1 == 7]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'str' and 'int'
>>> _list[(test0 == "string") & (test1 == 7)]
4

The interpreter appears to be interpreting the & first, instead of the == first.

Python Documentation states that order of evaluation should be == then &

Is this a bug in the Python interpreter? I'm using 3.6.3

Upvotes: 0

Views: 64

Answers (1)

John Kugelman
John Kugelman

Reputation: 362097

According to §6.16. Operator precedence, == has lower precedence than &. Confusingly, the table lists operators from lowest to highest precedence. (I had to stare at it for a minute to make sure I was reading it right.)

That means that expression is parsed as:

_list[test0 == ("string" & test1) == 7]

Upvotes: 4

Related Questions