[Python-ideas] Where-statement (Proposal for function expressions)

George Sakkis george.sakkis at gmail.com
Thu Jul 16 18:05:19 CEST 2009


On Thu, Jul 16, 2009 at 10:51 AM, Chris Perkins<chrisperkins99 at gmail.com> wrote:

> This idea is really growing on me.
>
> Here's another example - how do you calculate sample variance? You're
> probably thinking "Um, well, I think it's the square root of the sum
> of the squares minus the square of the sums". Great, that's a high-ish
> level, intuitive description of the algorithm. The precise details of
> how to go about calculating that are not important yet. So write it
> that way:
>
> def variance(data):
>    return sqrt(sum_of_squares - square_of_sums) where:
>        ... elided ...
>
> There - we've written the core of the algorithm at the same level of
> abstraction as we think about it. The code matches our mental model.
> Only then do we go about filling in the boring details.
>
> def variance(data):
>    return sqrt(sum_of_squares - square_of_sums) where:
>        def sqrt(v): return v ** 0.5
>        sum_of_squares = sum(v**2 for v in data)
>        square_of_sums = sum(data) ** 2
>
> The advantage is that now readers of the code, having developed some
> intuition about what "where blocks" mean, can see at a glance that the
> code at the first level of indentation is the important stuff, and the
> indented block is the implementation details; the stuff that's at a
> lower level of abstraction.

I realize the appeal of this but I see two issues with it:

- What you call an advantage can be a disadvantage for many
programmers used to the standard bottom-up way most procedural and
object-oriented languages support. For better or for worse, thinking
sequentially feels more natural than in terms of top-down levels of
abstractions. Unless one is (or gets) used to this style, "where"
blocks would be the code equivalent of top-posting; it doesn't make
sense unless you read it backwards.

- TIMTOWTDI. In any case, bottom-up won't go away so for any
non-trivial piece of code one has to choose between two equivalent
ways of expressing it. Think of Perl's "STATEMENT (if|unless) (EXPR)".

I'm not saying that these are necessarily show stoppers but they
should be addressed to see whether the benefits are worth the added
complexity.

George



More information about the Python-ideas mailing list