[Python-ideas] a in x or in y

Haoyi Li haoyi.sg at gmail.com
Thu Feb 13 22:20:22 CET 2014


Ah, I did not think about the laziness. That indeed is a pain since we
can't create our own custom lazy operators/methods.

I would say the correct answer is that we should let people define their
own lazy operators, and then define *or_in* or whatever as a lazy
operator/method, but I'm sure others would disagree.


On Thu, Feb 13, 2014 at 1:11 PM, Steven D'Aprano <steve at pearwood.info>wrote:

> 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
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140213/86cb44ba/attachment-0001.html>


More information about the Python-ideas mailing list