Functional Python Programming

(Wang) #1
Chapter 8

Two approaches to filtering with filterfalse() and filter()


In Chapter 5, Higher-order Functions we looked at the built-in filter() function.
The filterfalse() function from the itertools module could be defined from
the filter() function, as follows:


filterfalse = lambda pred, iterable:


filter(lambda x: not pred(x), iterable)


As with the filter() function, the predicate function can be of None value. The
value of the filter(None, iterable) method is all the True values in the iterable.
The value of the filterfalse(None, iterable) method is all of the False values
from the iterable:





filter(None, [0, False, 1, 2])





<filter object at 0x101b43a50>





list(_)





[1, 2]





filterfalse(None, [0, False, 1, 2])





<itertools.filterfalse object at 0x101b43a50>





list(_)





[0, False]


The point of having the filterfalse() function is to promote reuse. If we have a
succinct function that makes a filter decision, we should be able to use that function
to partition input in to pass and reject groups without having to fiddle around with
logical negation.


The idea is to execute the following commands:


iter_1, iter_2 = iter(some_source), iter(some_source)


good = filter(test, iter_1)


bad = filterfalse(test, iter_2)


This will obviously include all items from the source. The test() function is
unchanged, and we can't introduce a subtle logic bug through improper use of ().

Free download pdf