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

六眼飞鱼酱① 提交于 2019-11-28 08:03:15

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/38296689/where-in-the-python-docs-does-it-allow-the-in-operator-to-be-chained

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!