[Python-ideas] Temporary variables in comprehensions

Martin Teichmann lkb.teichmann at gmail.com
Fri Feb 16 11:24:10 EST 2018


Hi list,

> But when it comes to something like
> [f(x) + g(f(x)) for x in range(10)]
> you find you have to sacrifice some readableness if you don't want two
f(x)
> which might slow down your code.
>
> Someone may argue that one can write
> [y + g(y) for y in [f(x) for x in range(10)]]

personally I think that the biggest problem readability-wise is that "for"
is a post-fix operator, which makes generators much harder to read. It's
also very different from normal for loops, which have the "for" at the top.
IMHO generators would be much easier to read with a prefix for, as in

    [for x in range(10): f(x) + g(f(x))]

also nested generators get nicer like that:

    [for y in (for x in range(10): f(x)):
          y + g(y)]

one could critique here that we shouldn't use colons in expressions, but
that boat has sailed: we use them for lambdas. We do not write

     sq = x**2 lambda x

and I am not proposing that.

Also if/else could be written with colons, but I am not sure whether that's
actually nicer:

    val = (if attr is None: 5 else: attr + 3)

but it certainly is in case of ifs in generators:

    [for x in range(10):
         if x % 3 != 2: x]

which could be problematic to parse if you compare that to

    [for x in range(10):
         if x % 3 == 2: x - 1
         else: x + 1]

one could even dig out the often-proposed always-rejected
except-in-expression:

    [for x in range(10):
         try: f(x)
         except WhateverError: None]

or even a with:

    [for x in file_names:
         with open(x) as f:
             f.read()]


Greetings

Martin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180216/2b93c9d3/attachment.html>


More information about the Python-ideas mailing list