[Python-Dev] Re: Fwd: summing a bunch of numbers (or "whatevers")

David Abrahams dave@boost-consulting.com
Wed, 23 Apr 2003 05:50:59 -0400

Tim Peters <tim.one@comcast.net> writes:

> [Greg Ward]
>> Hmmm, a random idea: has filter() ever been used for anything else?
>> I didn't think so.  So why not remove everything *except* that handy
>> special-case: ie. in 3.0, filter(seq) == filter(None, seq) today, and
>> that's *all* filter() does.
>> Just a random thought...
> It's been used for lots of other stuff, but I'm not sure if any other use
> wouldn't read better as a listcomp.  For example, from spambayes:
> def textparts(msg):
>     """Return a set of all msg parts with content maintype 'text'."""
>     return Set(filter(lambda part: part.get_content_maintype() == 'text',
>                       msg.walk()))
> I think that reads better as:
>     return Set([part for part in msg.walk()
>                      if part.get_content_maintype() == 'text'])

IMO this one's much nicer than either of those:

     return Set(
         filter_(msg.walk(), _1.get_content_maintype() == 'text')


   filter_ = lambda x,y: filter y,x

and _N for N in 0..9 left as an exercise to the reader.

It helps my brain a lot to be able to write the sequence before the
filtering function, and for the kind of simple lambdas that Python is
restricted to, having to name the arguments is just syntactic

   python = best_language([pound for pound in the_world])

but-list-comprehensions-always-read-like-strange-english-to-me-ly y'rs,

Dave Abrahams
Boost Consulting