Can somebody explain this for me?
>>> None is None is None
True
>>> (None is None) is None
False
Doesn't the 'is' operator take 2 operands, compare objects from the left, and return Boolean?
Can somebody explain this for me?
>>> None is None is None
True
>>> (None is None) is None
False
Doesn't the 'is' operator take 2 operands, compare objects from the left, and return Boolean?
Because it is being interpreted as a chained comparison:
comparison ::= or_expr ( comp_operator or_expr )*
comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "!="
| "is" ["not"] | ["not"] "in"
Comparisons can be chained arbitrarily, e.g.,
x < y <= z
is equivalent tox < y and y <= z
, except that y is evaluated only once (but in both cases z is not evaluated at all whenx < y
is found to be false).Formally, if
a, b, c, …, y, z
are expressions andop1, op2, …, opN
are comparison operators, thena op1 b op2 c ... y opN z
is equivalent toa op1 b and b op2 c and ... y opN z
, except that each expression is evaluated at most once.
Thus, since is
is a comparison operator, your first expression is equivalent to:
None is None and None is None
Compare with 2 < 3 < 4
.
Is the 2nd None the same as the 1st None? Yes. Is the 3rd same as the 2nd? Yes.
OTOH, (True) is None
is clearly False. The parentheses broke the chaining.
Evaluating lo < n < hi
is a common python idiom, and that doesn't make you worried about an intermediate result of True < 4
. Evaluating x is y is z
is less common, but for your singleton None
the three objects are identical.