[Python-Dev] Efficient predicates for the standard library

Raymond Hettinger python at rcn.com
Sat Oct 4 21:24:48 EDT 2003


[Christian Stork]
> So, I propose an implementation like this:
>
>    def all(seq, pred=bool):
>        return False not in imap(pred, seq)
>
>    def some(seq, pred=bool):
>        return True in imap(pred, seq)
>
>    def no(seq, pred=bool):
>        return True not in imap(pred, seq)

The examples are all useful by themselves, but their primary purpose is
to teach how to use the basic tools.  Accordingly, the examples should
not become complex and they should tie in as well as possible to
previously existing knowledge (i.e. common patterns for argument order).

Your proposal is a net gain and I will change the docs as requested.
Having bool() as a default makes the functions more useful and less
error prone.  Also, it increases instructional value by giving an
example of a predicate (for who skipped class that day).  Also, your
proposed argument order matches common mathematical usage (i.e. All
elements in a <domain> such that <predicate> is true).

For your own purposes, consider using a faster implementation:

    def Some(seq, pred=None):
        for x in ifilter(None, seq):
            return True
        return False

All() and No() have similar fast implementations using ifilterfalse()
and reversing the return values.



> For enhanced assert support I'd advocate additional predicates for
> easy and fast type checking, eg allListType, allIntType, etc.

> Maybe all this should go into it's own `preds' module?

Or maybe not ;-)

Somewhere, Tim has a eloquent and pithy saying which roughly translates
to:

"""Adding trivial functions is a net loss because the burden of learning
or becoming aware of them (and their implementation nuances) will far
exceed the microscopic benefit of saving a line or two that could be
coded on the spot as needed."""

In this case, a single example in the docs may suffice:

    if False in imap(isinstance, seqn, repeat(int)):
        raise TypeError("All arguments must be of type int")
    

Raymond Hettinger




More information about the Python-Dev mailing list