On 09/08/2019 18:10, Brett Cannon wrote:
On Fri, Aug 9, 2019 at 9:03 AM Peter O'Connor <peter.ed.ocon...@gmail.com>
wrote:

Alright hear me out here:

I've often found that it would be useful for the following type of
expression to be condensed to a one-liner:

def running_average(x_seq):
     averages = []
     avg = 0
     for t, x in enumerate(x_seq):
         avg =  avg*t/(t+1) + x/(t+1)
         averages.append(avg)
     return averages

Because really, there's only one line doing the heavy lifting here, the
rest is kind of boilerplate.


But it's boilerplate that communicates the starting state of your loop
which is useful to know and to have be very clearly communicated.

+1.  The intent and operation of your code is clear.  Win.

Then I learned about the beautiful and terrible "for x in [value]":

def running_average(x_seq):
     return [avg for avg in [0] for t, x in enumerate(x_seq) for avg in
[avg*t/(t+1) + x/(t+1)]]

Many people find this objectionable because it looks like there are 3 for
loops, but really there's only one: loops 0 and 2 are actually assignments.

I find it objectionable because it's unreadable. I would reject this in a code review as "too clever for its own good," therefore unnecessarily hard to maintain.

**My Proposal**

What if we just officially bless this "using for as a temporary
assignment" arrangement, and allow "for x=value" to mean "assign within the
scope of this for".  It would be identical to "for x in [value]", just more
readable.  The running average function would then be:

def running_average(x_seq):
     return [avg for avg=0 for t, x in enumerate(x_seq) for avg = avg *
t/(t+1) + x / (t+1)]


I personally don't find that more readable then the unrolled version you're
trying to avoid. And based on the amount of grief we got for the walrus
operator I wouldn't expect much uptake on this as being considered more
readable by others either. (And remember that "Readability counts").

Agreed.

--
Rhodri James *-* Kynesim Ltd
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/MO4G7T7H7BPWI2KLWDYQJQ7B7XEHJO2J/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to