feature request: mul

Steven Taschuk staschuk at telusplanet.net
Wed Jun 11 14:38:50 EDT 2003


Quoth Michele Simionato:
  [...]
> At the present, instead of
> 
> if condition[0] or condition[1] or ....  or condition[42]:
>     dosomething()
> 
> I can use (using a comment to make crystal clear what the code is doing)
> 
> if sum(condition): # multi_or
>    dosomething() 

Imho this is an abuse of sum().  Note that it depends on exactly
which true and false values are used:

    >>> condition = [1, -1]
    >>> if condition[0] or condition[1]:
    ...     print 'foo'
    ... 
    foo
    >>> if sum(condition):
    ...     print 'foo'
    ... 
    >>> 

This kind of thing could make for subtle bugs if you get into the
habit of thinking of 'sum(L)' as a logical instead of an
arithmetic operation.

(If we had a boolean type which was unrelated to ints, and that
type had __add__ and __mul__ implementations which fit with
boolean algebra, and ints and booleans could not be added without
explicit conversion, then I'd be happy with using sum() on a list
of booleans.  But this is not the case.)

Another, much more minor, matter: sum() doesn't short-circuit.  I
don't imagine this would matter unless len(condition) is quite
large.

  [...]
> if mul(condition): # multi_and
>    dosomething()

If a mul() existed, this would be less prone to bugs than the
corresponding use of sum(), but it's still not a reliable way to
rewrite the series of ands; for example, consider
    condition = ['foo', '']

  [...]
> Apart for boolean algebra, I think a 'mul' with
> the signature
> 
> mul(iterable, start=1)
> 
> would naturally complement 'sum'. Moreover, 
> the implementation would be trivial and I don't 
> see why we should not have it.

It would naturally complement 'sum', though I wonder whether
'product' wouldn't be a better name.  ('mul' is parallel to 'add',
not 'sum'.)

I'm not sure it's commonly enough needed to deserve a built-in,
though.  If sum, min and max get moved out to a module, I'd
certainly be in favour of a 'product' function too.  But in no
case would I want to use these functions for boolean algebra.

  [...]
-- 
Steven Taschuk                            staschuk at telusplanet.net
"Our analysis begins with two outrageous benchmarks."
  -- "Implementation strategies for continuations", Clinger et al.





More information about the Python-list mailing list