2
>>> a = 2
>>> b = 3
>>> c = 2
>>> b > a == c
True
>>>

Is this true that b > a == c is equal to a < b and c == a because it's a chained comparison?

This doesn't make sense to me because of == comparison, I would expect that b > a == c is equal to (b > a) == c or b > (a == c).

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
warvariuc
  • 57,116
  • 41
  • 173
  • 227
  • Chaining works with any comparison operator, `a op b op c` is equivalent to `(a op b) and (b op c)` – Barmar Sep 24 '19 at 16:20
  • With the slight difference in behavior that `a op b op c` only has to compute/load `b` once, where `(a op b) and (b op c)` would have to do so twice. Specific answer on duplicate that addresses your problem is [Chaining comparison operators](https://stackoverflow.com/a/101945/364696). – ShadowRanger Sep 24 '19 at 16:24
  • According to the comment from @Barmar operator priority doesn't work in this case, because it's a chained comparison which results to `(a < b) and (c == a)` – warvariuc Sep 24 '19 at 16:33
  • @Massifox: Incorrect. All the comparison operators (aside from boolean operators `or`, `and` and `not`) [have equal precedence](https://docs.python.org/3/reference/expressions.html#operator-precedence). The parentheses simply prevent the chaining from operating at all, so you simply have one unchained comparison within the parentheses, with the result used in an unchained comparison outside the parentheses). – ShadowRanger Sep 24 '19 at 16:34

1 Answers1

0

python is correcting your comparison automatically with if (b>a) AND (a==c)

Eirik Fesker
  • 328
  • 1
  • 12
  • 1
    "correcting" implies the code was wrong in some way and Python had to fix it. The Python language spec intentionally supports this design; it's just unusual (and likely a programmer mistake) to use it to chain greater-than with equality testing. – ShadowRanger Sep 24 '19 at 16:23
  • "and likely a programmer mistake". That's the thing: PyCharm suggests to simplify `a < b and c == a` and it looks wrong. – warvariuc Sep 24 '19 at 16:28
  • @warvariuc: The PyCharm simplification is largely correct (aside from `a < b` possibly behaving differently from `b > a`, same for `a == c` vs. `c == a`). It has to load `a` twice, but it's less confusing. If the PyCharm simplification is wrong, it probably means you didn't write what you intended, and need additional parentheses to correct it to `(b > a) == c` or `b > (a == c)` (assuming one of those was the intent). Comparison chaining is much more intuitive for stuff like range testing, e.g. `if 0 < x < 10:` as a simple way to check if `x` is between `0` and `10` (exclusive). – ShadowRanger Sep 24 '19 at 16:31
  • @ShadowRanger See https://youtrack.jetbrains.com/issue/PY-37991 That's where my question came from. – warvariuc Sep 24 '19 at 16:37