Python Iterables struggling using map() built-in

Steven D'Aprano steve at pearwood.info
Tue Dec 9 01:40:05 EST 2014


On Tue, 09 Dec 2014 00:03:33 -0500, Terry Reedy wrote:

> On 12/8/2014 9:50 PM, Steven D'Aprano wrote:
>> Roy Smith wrote:
>>
>>> Chris Angelico wrote:
> 
>>>> def myzip(*args):
>>>>      iters = map(iter, args)
>>>>      while iters:
>>>>          res = [next(i) for i in iters]
>>>>          yield tuple(res)
>>>
>>> Ugh.  When I see "while foo", my brain says, "OK, you're about to see
>>> a loop which is controlled by the value of foo being changed inside
>>> the loop".
>>
>> Yes. Me too. 99% of the time when you see "while foo", that's what
>> you'll get, so it's the safe assumption. But it's only an assumption,
>> not a requirement. When you read a bit more of the code and see that
>> iters isn't being modified, your reaction ought to be closer "oh wow,
>> that's neat"
> 
> To me it is a code smell.  iters is empty if and only if args is empty.
>   If args is empty, iters should not be created.
> 
> if args:
>    iters = ...
>    while True
>      ... (return on exception)
> 
> makes the logic clear.

When you understand why this body of code is inelegant and ugly, you 
should understand why the above is inelegant and ugly:

def double(x):
    if x != 0:
        x *= 2
    return x




-- 
Steven



More information about the Python-list mailing list