[Python-ideas] Explicit variable capture list

Andrew Barnert abarnert at yahoo.com
Mon Jan 25 16:42:08 EST 2016


On Jan 23, 2016, at 19:22, Nick Coghlan <ncoghlan at gmail.com> wrote:
> 
> Accordingly, a statement like:
> 
>    powers = []
>    for new i in range(10):
>        def f(x):
>            return x**i
>       powers.append(f)
> 
> Could be semantically equivalent to:
> 
>    powers = []
>    for i in range(10):
>        def _for_loop_suite(i=i):
>            def f(x):
>                return x**i
>           powers.append(f)
>        _for_loop_suite()
>        del _for_loop_suite

A simpler translation of the Swift/C#/etc. behavior might be:

>    powers = []
>    for i in range(10):
>        def _for_loop_suite(i):
>            def f(x):
>                return x**i
>           powers.append(f)
>        _for_loop_suite(i)
>        del _for_loop_suite


This is, after all, how comprehensions work, and how you mechanically translate let bindings from other languages to Python (I believe MacroPy even has a let macro that does exactly this); it's slightly simpler to understand under the hood; it's even slightly more efficient (not that it will ever matter).

Of course that raises an important point: when you're _not_ mechanically translating, you rarely translate a let this way; instead, you translate it by rewriting the code at a higher level. (And the fact that this translation _is_ idiomatic in JavaScript is exactly why JS code is ugly in the way that Guido and others decry in this thread.) Do we want the compiler doing something under the hood that we wouldn't want to write ourselves? (Again, people in JS, and other languages like C#, don't consider that a problem--both languages define async as effectively a macro that transforms your code into something you wouldn't want to look at, and those kinds of macros are almost the whole point of Lisp, but I think part of why people like Python is that the semantics of most sugar can be described in terms that are just as readable as the sugared version, except for being longer.)

That's why I think I prefer not-Terry's (sorry for the misattribution) version: if something is going to act differently from the usual semantics, maybe it's better to describe it honestly as a new rule you have to learn, than to describe it as a translation to code that has familiar semantics but is nowhere near idiomatic.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160125/ab2aaf17/attachment.html>


More information about the Python-ideas mailing list