pythonstringexpressionmembership

What's going on with the chaining in Python's string membership tests?


I just realized I had a typo in my membership test and was worried this bug had been causing issues for a while. However, the code had behaved just as expected. Example:

"test" in "testing" in "testing" in "testing"

This left me wondering how this membership expression works and why it's allowed.

I tried applying some order of operations logic to it with parentheses but that just breaks the expression. And the docs don't mention anything about chaining. Is there a practical use case for this I am just not aware of?


Solution

  • in is a comparison operator. As described at the top of the section in the docs you linked to, all comparison operators can be chained:

    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 evaluated at most once.

    So:

    "test" in "testing" in "testing" in "testing"
    

    Is equivalent to:

    "test" in "testing" and "testing" in "testing" and "testing" in "testing"