1

Anyone have a description as to why this is giving behavior?

if (key in self.dict) == True:

vs

if key in self.dict == True:

My order of precedence table tells me these two operators should evaluate left to right, but for some reason I'm actually seeing incorrect behavior in the second example I gave. Does anyone know why the parenthesis are important here?

https://docs.python.org/3/reference/expressions.html#operator-precedence

From my understanding these two lines should evaluate exactly the same.

Reproducable:

Python 3.8.3 (tags/v3.8.3:6f8c832, May 13 2020, 22:20:19) [MSC v.1925 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> dict = {}
>>> dict[1] = 2
>>> 1 in dict
True
>>> 1 in dict == True
False
>>> (1 in dict) == True
True
>>> 1 in (dict == True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument of type 'bool' is not iterable
blurb
  • 600
  • 4
  • 20

1 Answers1

1

The relevant part is comparisons:

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z

So you have

key in dict and dict == True

This is very much a unique Python thing.

Nick
  • 138,499
  • 22
  • 57
  • 95
kabanus
  • 24,623
  • 6
  • 41
  • 74