[Python-ideas] Two small functional-style-related improvements

Terry Reedy tjreedy at udel.edu
Sun Mar 27 21:09:39 CEST 2011

On 3/27/2011 7:53 AM, Jan Kaliszewski wrote:

> Which one of the following do you prefer?
> * filter((lambda x: x is None), iterable)
> * filter(functools.partial(operator.is_, None), iterable)

These two produce an iterable of Nones, one for each None in the 
original iterable. I have trouble imagining a real use case for this.

I can see a use cases for dropping everything but None. This can, of 
course, always be done at the point of use:

for ob in iterable:
   if ob is not None:

If you want to separate the conditional from the action and hide the 
conditional, then write a trivial, specific, filter generator:

def dropNone(it):
   for ob in it:
     if ob is not None:
       yield ob

for ob in dropNone(iterable):

For repeated use, I prefer dropNone to any filter version, including 
your proposal.

> * filter(None, (x is None for x in iterable))

This is not the same thing as the above as it instead produces an 
iterable of Trues, one for each None in iterable.

Terry Jan Reedy

More information about the Python-ideas mailing list