[Python-ideas] Introducing where clauses

Nick Coghlan ncoghlan at gmail.com
Mon Jun 22 12:40:05 CEST 2009

Andrey Popp wrote:
> value f(y) calculates three times -- It is a problem if function f
> takes much time to compute its value or has side effects. If we would
> have where clause, we can rewrite expression above with:
>     [(y, y) for x in some_iterable if y < 2 where y = f(x)]
> I think it is really useful. We can also expand this idea to lambdas
> or maybe to introducing arbitrary scoping blocks of code.

Or you could just bite the bullet and write a custom generator:

  def g(iterable):
    for x in iterable:
      y = f(x)
      if y < 2:
        yield (y, y)

Give it a meaningful name and docstring and it can even be self-documenting.

Lambdas, comprehensions and expressions in general all have limits -
usually deliberate ones. When one runs up against those limits it is a
hint that it is time to switch to using multiple statements (typically
factored out into a function that can be substituted for the original
inline expression)

But then, I'll freely confess to not really understanding the apparently
common obsession with wanting to be able to do everything as an expression.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list