[Python-ideas] Allow filter(items)
Peter Otten
__peter__ at web.de
Tue Aug 6 09:28:29 CEST 2013
Chris Angelico wrote:
> On Mon, Aug 5, 2013 at 8:46 AM, Peter Otten
> <__peter__ at web.de> wrote:
>> filter(items)
>>
>> looks much cleaner than
>>
>> filter(None, items)
>>
>> and is easy to understand. Fewer people would use alternative spellings
>> like
>>
>> filter(bool, items)
>
> As an alternative (and simpler) to the proposal currently on the
> table: Would it improve clarity if the magic of None were instead
> applied to 'bool'?
I was really thinking of the Python side. There is a first_true() function
as a candidate for inclusion into itertools which is basically
next(filter(None, items), None)
and I felt that e. g.
next(filter(None, (line.strip() for line in file)), "")
warrants a new function while
next(filter(line.strip() for line in file), "")
does not. Looks like it won't fly...
The implementation already has an optimization to treat bool like None --
the former is never called:
[Python/bltinmodule.c]
if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
ok = PyObject_IsTrue(item);
This is done on every next() call, and while my instinct would be to
translate PyBool_Type to Py_None once in the constructor I doubt that this
has a noticeable impact on performance.
> The third spelling here would thus be blessed with
> a usage recommendation and possible performance improvement
> (eliminating a redundant call, but only if the arg 'is bool'), while
> still having most of the readability that the one-arg form aims for.
> (Obviously backward compat will mean that None will continue to have
> its magic, but it would be the less-recommended option. New code would
> be encouraged to use filter(bool,...) which would have the exact same
> effect.)
>
> ChrisA
More information about the Python-ideas
mailing list