[Python-ideas] a in x or in y

Steven D'Aprano steve at pearwood.info
Fri Feb 14 13:15:56 CET 2014


On Thu, Feb 13, 2014 at 04:34:12PM -0800, Ethan Furman wrote:
> On 02/13/2014 03:49 PM, Ram Rachum wrote:
> >On Fri, Feb 14, 2014 at 1:46 AM, Greg Ewing wrote:
> >>
> >>class either(object):
> >>
> >>     def __init__(self, *args):
> >>         self.args = args
> >>
> >>     def __contains__(self, x):
> >>         for a in self.args:
> >>             if x in a:
> >>                 return True
> >>         return False
[...]
> >Also, this doesn't allow lazy evaluation.
> 
> Certainly it does.  If the target is in the first thing it returns True at 
> that point.

No, Ram is correct. either() short circuits the `x in a` tests, but it 
evaluates the individual args eagerly, not lazily.

For simplicity, let's just talk about two elements, rather than 
arbitrary numbers, and compare lazy and non-lazy evaluation. Contrast 
how Python's short-circuiting `and` works compared to this not-quite 
equivalent:

x and 1/x  # 1/x is only evaluated if x is not zero

def and_(a, b):
    if a:
        return b
    return a

and_(x, 1/x)  # 1/x is evaluated before and_ even sees it


Because Python's short-circuiting operators are syntax, they can avoid 
evaluating the operand they don't need. The same doesn't apply to Greg's 
"either" class, you have to evaluate all the terms first. It can 
short-circuit calling the __contains__ methods, but that's all.


-- 
Steven


More information about the Python-ideas mailing list