Python Iterables struggling using map() built-in

Steven D'Aprano steve at pearwood.info
Mon Dec 8 04:40:46 EST 2014


On Mon, 08 Dec 2014 11:35:36 +1100, Chris Angelico wrote:

> On Mon, Dec 8, 2014 at 11:27 AM, Roy Smith <roy at panix.com> wrote:
>> Although, to be honest, I'm wondering if this is more straight-forward
>> (also not tested):
>>
>> def myzip37(*args):
>>     if not args:
>>         return
>>     iters = list(map(iter, args))
> 
> Yes, I prefer this too. It's explicit and clear that passing no
> arguments will yield no values.

The first version is explicit and clear too. I'm sorry to say this, but 
it is true: if you (generic you) don't recognise that

    while iters:
        ...


skips the while block if iters is an empty list, then *you* have a 
problem, not the code. You're simply not fluent with the language. (Or 
you have a strange blind-spot, in which case you have my sympathy but 
that's your problem to deal with, not mine.) This is not an obscure 
corner of some rarely-used library that has a strange and weird API, it 
is a fundamental part of Python.

I *guarantee* that there are people who will bitch and moan about your 
example too, and insist that the only "right" way to write it is to be 
"explicit" that an empty tuple is falsey:

    if not args == ():
        return

and there will be some who are convinced that operator precedence is too 
"implicit":

    if not (args == ()):   # args != () is okay too
        return


Dumbing down code is an anti-pattern, because there's always somebody 
just a little less fluent in the language who will complain that it isn't 
dumbed down enough.

Sometimes we have this meme that if you can't take in code at a glance 
and instantly understand it, it's bad code. But that meme is untrue, and 
we all know that it is untrue: real world code is often hard to 
understand because it can't be any simpler. Try understanding the code 
for a web server, or code that calculates the square root of a number, or 
code for importing a module.

Occasionally, very occasionally, we have a combination of programming 
language and algorithm which combines in such a way that you can actually 
implement a useful algorithm in a simple, elegant, minimalist way. As 
programmers, we all know how fecking rare this is: we start with an 
elegant five line function, and by the time we cover all the corners and 
fix the bugs it's twenty lines and you can't tell what it does any more 
without studying it for ten minutes. zip() is an exception, you can write 
zip() in Python beautifully. It breaks my heart that there are people who 
think that it is improved by adding unnecessary guard clauses to it.



-- 
Steven



More information about the Python-list mailing list