[Python-ideas] Introducing where clauses

Carl Johnson cmjohnson.mailinglist at gmail.com
Tue Jun 23 01:15:04 CEST 2009


Andrey Popp wrote:

> I am not about list comprehension only, there are other cases for
> where-clause, for example lambdas:
>
>    f = lambda x: (x, y) if x > 0 else (x, 0) where y = g(x)

Yuck. This reminds me of why I gave up on the Haskell tutorial I was
working through. The reading of this line keeps bouncing back and
forth. "OK, function f, passing in x, returning x, y… Wait? What's y?
Is that from an external scope? Anyway, here's an if-else clause, and
oh, there's the y! It's the same as g(x). OK, so where all did they
use y? Hmm, lets see, looks like just the one spot…" This would be
much easier to grasp as a function:

def f(x):
    y = g(x)
    if y > 0:
        return x, y
    else:
        return x, 0

This version makes the parallelism between the two return values much
more clear: "Oh, OK, it's always going to return x as the first in the
tuple, and the second value will be either g(x) or 0, whichever is
greater." We might even re-write it as

def f(x):
    y = g(x)
    r = y if y > 0 else 0
    return x, r

to make it shorter.


-- Carl



More information about the Python-ideas mailing list