From 1a21e693814d63d45d0528680740f82b3d04cf80 Mon Sep 17 00:00:00 2001 From: Andrew Grangaard Date: Wed, 7 Oct 2020 11:11:18 -0700 Subject: [PATCH] Docs: improve equivalence expression for chained comparison Add grouping parenthesis around the equivalence expression to make it clear that it is evaluated as a single expression. `x < y < z` parses as a single expression, so while it is equivalent to x < y and y < z in isolation, it is different when used in an expression with `not`. `not` has a higher precedence than `and`. We don't see this with `or` as it has a lower precedence than `and`. (See the next section on Boolean Expressions) + `not x < y < z` == `not (x < y < z)` + `not x < y and y < z` != `not (x < y and y < z)` ``` >>> import ast >>> ast.dump(ast.parse('not x>> ast.dump(ast.parse('not x < y and y < z')) == ast.dump(ast.parse('(not x < y) and y < z')) True >>> ast.dump(ast.parse('not x < y and y < z')) == ast.dump(ast.parse('not (x < y and y < z)')) False ``` --- Doc/reference/expressions.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Doc/reference/expressions.rst b/Doc/reference/expressions.rst index b68c29860cf..9cbbc10f8c9 100644 --- a/Doc/reference/expressions.rst +++ b/Doc/reference/expressions.rst @@ -1359,12 +1359,12 @@ Comparisons yield boolean values: ``True`` or ``False``. .. index:: pair: chaining; comparisons Comparisons can be chained arbitrarily, e.g., ``x < y <= z`` is equivalent to -``x < y and y <= z``, except that ``y`` is evaluated only once (but in both +``( x < y and y <= z )``, except that ``y`` is evaluated only once (but in both cases ``z`` is not evaluated at all when ``x < y`` is found to be false). Formally, if *a*, *b*, *c*, ..., *y*, *z* are expressions and *op1*, *op2*, ..., *opN* are comparison operators, then ``a op1 b op2 c ... y opN z`` is equivalent -to ``a op1 b and b op2 c and ... y opN z``, except that each expression is +to a single expression ``( a op1 b and b op2 c and ... y opN z )``, except that each expression is evaluated at most once. Note that ``a op1 b op2 c`` doesn't imply any kind of comparison between *a* and