Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where in the python docs does it allow the `in` operator to be chained?

I recently discovered that the following returns True:

'a' in 'ab' in 'abc'

I'm aware of the python comparison chaining such as a < b < c, but I can't see anything in the docs about this being legal.

Is this an accidental feature in the implementation of CPython, or is this behaviour specified?

like image 390
Eric Avatar asked Jul 10 '16 21:07

Eric


1 Answers

This is fully specified behaviour, not an accidental feature. Operator chaining is defined in the Comparison operators section:

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 cases z is not evaluated at all when x < y is found to be false).

in is one of the comparison operators; from the same section:

comp_operator ::=  "<" | ">" | "==" | ">=" | "<=" | "<>" | "!="
                   | "is" ["not"] | ["not"] "in"

No exceptions are made for combinations that may not make much sense.

The specific expression you used as an example is thus executed as 'a' in 'ab' and 'ab' in 'abc', with the 'ab' literal only being executed (loaded) once.

like image 141
Martijn Pieters Avatar answered Sep 30 '22 16:09

Martijn Pieters