[Python-ideas] Proposal: A Reduce-Map Comprehension and a "last" builtin

Chris Angelico rosuav at gmail.com
Thu Apr 5 21:02:30 EDT 2018


On Fri, Apr 6, 2018 at 10:37 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> On Thu, Apr 05, 2018 at 05:31:41PM -0700, Ethan Furman wrote:
>> On 04/05/2018 03:24 PM, Peter O'Connor wrote:
>>
>> >Well, whether you factor out the loop-function is a separate issue.  Lets
>> >say we do:
>> >
>> >     smooth_signal = [average = compute_avg(average, x) for x in signal
>> >     from average=0]
>> >
>> >Is just as readable and maintainable as your expanded version, but saves 4
>> >lines of code.  What's not to love?
>>
>> It is not readable and it is not Python (and hopefully never will be).
>
> Be fair. Strip out the last "from average = 0" and we have little that
> isn't either in Python or is currently being proposed elsewhere. Change
> the syntax for assignment within the comprehension to one of the
> preferred syntax variants from last month's "Statement local name
> bindings" thread, and we have something that is strongly being
> considered:
>
>     [(average := compute_avg(average, x)) for x in signal]
>
>     [(compute_avg(average, x) as average) for x in signal]
>
> All we need now is a way to feed in the initial value for average. And
> that could be as trival as assigning a local name for it:
>
>     average = 0
>
> before running the comprehension.

That would only work if the comprehension is executed in the same
context as the surrounding code, instead of (as currently) being in a
nested function. Otherwise, there'd need to be an initializer inside
the comprehension - but that can be done (although it won't be
particularly beautiful).

ChrisA


More information about the Python-ideas mailing list