[Python-ideas] a in x or in y

Steven D'Aprano steve at pearwood.info
Thu Feb 13 22:11:35 CET 2014


On Thu, Feb 13, 2014 at 10:51:22AM -0800, Haoyi Li wrote:
> I think we're talking about the wrong thing by focusing on whether we want
> "or in" or "or" or other finnicky syntax things. In terms of whether we can
> express the logic the OP wanted, we already can:
> 
> *>>> a = {1, 2, 3}*
> *>>> b = {4, 5, 6}*
> *>>> c = 5*
> *>>> c in a | b*
> *True*
> 
> Perfectly concisely, with the exact semantics we want,

But they are not the same semantics! They are *quite different* 
semantics. You may have lead yourself astray because the result of:

    c in a or c in b

happens to give the same result as:

    c in a|b

for the specific values of a, b, c given. But they actually perform 
semantically different things: the first one lazily performs two 
separate containment tests, while the second eagerly calculates the 
union of two sets a|b and then performs a single non-lazy containment 
test.

Because the first form is lazy, this succeeds:

a = {1, 2, 3}
b = None
c = 2
c in a or c in b

(admittedly it succeeds by accident) while your eager version needs to 
be re-written as:

c in (a|b if b is not None else a)

in order to avoid failure.

Another problem: since the __or__ operator can be over-ridden, you 
cannot afford to assume that a|b will always be a union. Or it might 
have side-effects. __contains__ also can be over-ridden, and might also 
have side-effects, but in general they will be *different* side-effects.


-- 
Steven


More information about the Python-ideas mailing list