[PEP] matching and mismatching (fwd)

Lulu of the Lotus-Eaters mertz at gnosis.cx
Thu May 2 14:18:16 EDT 2002


|There was a proposal to make 'generator comprehensions', with a syntax
|like
|    for x in [yield line in file if len(strip(line))]:
|	    print x
|but it was rejected.  (http://python.org/peps/pep-0289.html)

I think the same PEP discussed some lazy FP functions (I'm lazy now,
maybe it was a different PEP).  In any case, writing you own is really
easy:

    def xfilter(predicate, iterable):
        if predicate is None:       # Compat with filter()
            predicate = lambda: 1
        for item in iterable:
            if predicate(item):
                yield item

Once you have it, calling it without the need to read the whole list is
simple:

    for line in xfilter(lambda l: len(strip(l)), file):
        print line

Of course, the lambda is harder to read, better would be:

    def nonempty: return len(strip(l))
    for line in xfilter(nonempty, file):
        print line

--
    _/_/_/ THIS MESSAGE WAS BROUGHT TO YOU BY: Postmodern Enterprises _/_/_/
   _/_/    ~~~~~~~~~~~~~~~~~~~~[mertz at gnosis.cx]~~~~~~~~~~~~~~~~~~~~~  _/_/
  _/_/  The opinions expressed here must be those of my employer...   _/_/
 _/_/_/_/_/_/_/_/_/_/ Surely you don't think that *I* believe them!  _/_/






More information about the Python-list mailing list