The Cost of Dynamism (was Re: Pyhon 2.x or 3.x, which is faster?)

Chris Angelico rosuav at gmail.com
Tue Mar 22 09:24:20 EDT 2016


On Wed, Mar 23, 2016 at 12:15 AM, Jussi Piitulainen
<jussi.piitulainen at helsinki.fi> wrote:
> Chris Angelico writes:
>
>> On Tue, Mar 22, 2016 at 11:52 PM, Jussi Piitulainen wrote:
>>> Now you can ask for the next item that satisfies a condition using a
>>> generator expression:
>>>
>>> next(symbol for symbol in stream if not symbol.isspace())
>>> ---> '/'
>>>
>>> next(symbol for symbol in stream if not symbol.isspace())
>>> ---> '*'
>>
>> Or use filter(), which is sometimes clearer:
>>
>> # You probably want a more sophisticated function here
>> def nonspace(ch): return not ch.isspace()
>>
>> next(filter(nonspace, stream))
>
> Sure.
>
> # But there's more fun hiding in the standard library.
> next(itertools.filterfalse(operator.methodcaller('isspace'), stream))

... at that point, the genexp is miles ahead in readability :)

Although I do sometimes yearn for a "filterout" function that does the
same thing as filter() but negates its predicate. Then you could use:

next(filterout(str.isspace, stream))

to say "give me the next from the stream, filtering out those which
are spaces". It's not hard to write, of course.

ChrisA



More information about the Python-list mailing list