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

Chris Perkins chrisperkins99 at gmail.com
Thu Jul 16 19:58:21 CEST 2009


On Thu, Jul 16, 2009 at 1:13 PM, Steven D'Aprano<steve at pearwood.info> wrote:
> On Fri, 17 Jul 2009 12:51:54 am Chris Perkins wrote:
>
>> def variance(data):
>>     return sqrt(sum_of_squares - square_of_sums) where:
>>         ... elided ...
>
> That would actually be the standard deviation, not the variance.

Hence my use of "Um, I think it's..." :)
Yeah, I couldn't remember if this was right, but as you say below,
it's not the point of the example, so I didn't bother to look it up.

> I'm now going to try to convince you that this entire approach is
> actually harmful and should be avoided. You said:

[ .. snip me being almost - but not quite - convinced ...]

>
> def variance(data):
>    def sqrt(v):
>        return v**0.5
>    def sum_of_squares(data):
>        return sum(v**2 for v in data)
>    def square_of_sums(data):
>        return sum(data)**2
>    return sqrt(sum_of_squares(data) - square_of_sums(data))

This is the case that I was trying to present an alternative to. The
fact is, people _do_ write code like this. Sometimes pulling the local
stuff out into reusable functions is the right thing to do, but I
don't think it always is.

> In either case, writing the sums-and-squares before the return suggests
> that these are common code best written as re-usable functions.
> But "where" changes the focus of the coder away from factoring code
> *out* of functions into placing code *inside* internal blocks. It
> encourages the coder to think of sum_of_squares as a private
> implementation detail instead of a re-usable component. And that is, I
> believe, harmful.

But surely you agree that _sometimes_ there is code that really is an
implementation detail - not everything is reusable, or at least not
usefully reusable. Taking your argument to the extreme, every function
would be only one line of code. I prefer to trust programmers to make
the best use of the tools available to create good code.

In other words:

Jan Kaliszewski:
>Every language feature can be misused. More powerful feature -- larger
>possibilities of misusing. But language is not for substituting
>programmer's sense.

Yeah, ditto to what he said.


Chris Perkins



More information about the Python-ideas mailing list