[Python-ideas] several different needs [Explicit variable capture list]

Jim J. Jewett jimjjewett at gmail.com
Tue Jan 26 14:40:01 EST 2016


I think a small part of the confusion is that there are at least four
separate (albeit related) use cases.  They all use default arguments
for the current workarounds, but they don't have the same ideal
solution.


(1)  Auxiliary variables

    def f(x, _len=len): ...

This is often a micro-optimization; the _len keyword really shouldn't
be overridden.  Partly because it shouldn't be overridden, having it
in the signature is just ugly.

This could be solved with another separator in the signature, such as
; or a second () or a new keyword ...

    def f(x, aux _len=len): ...
    def f(x, once _len=len): ...

    def f(x; _len=len):...
    def f(x)(_len=len): ...
    def f(x){_len=len}: ...

But realistically, that _len isn't ugly *just* because it shouldn't be
overridden; it is also inherently ugly.  I would prefer that something
like Victor's FAT optimizer just make this idiom obsolete.

(2)  immutable bindings

once X
final Y
const Z

This is pretty similar to the auxiliary variables case, except that it
tends to be desired more outside of functions.  The immutability can
be worth documenting on its own, but it feels too much like a typing
declaration, which raises questions of "why *this* distinction for
*this* variable?"

So again, I think something like Victor's FAT optimizer (plus comments
when immutability really is important) is a better long-term solution,
but I'm not as sure as I was for case 1.

(3)  Persistent storage

    def f(x, _cached_results={}): ...

In the past, I've managed to convince myself that it is good to be
able to pass in a different cache ... or to turn the function into a
class, so that I could get to self, or even to attach attributes to
the function itself (so that rebinding the name to another function in
a naive manner would fail, rather than produces bugs).  Those
convincings don't stick very well, though.

This was clearly at least one of the motivations of some people who
asked about static variables.

I still think it might be nice to just have a way of easily opening a
new scope ... but then I have to explain why I can't just turn the
function into a class...

So in the end, I suspect this use case is better off ignored, but I am
pretty sure it will lead to some extra confusion if any of the others
are "solved" in a way that doesn't consider it.

(4)  Current Value Capture

This is the loop variable case that some have thought was the only
case under consideration.

I don't have anything to add to Andrew Barnert's
https://mail.python.org/pipermail/python-ideas/2016-January/037980.html

but do see Steven D'Aprano's
https://mail.python.org/pipermail/python-ideas/2016-January/038047.html
 for gotchas even within this use case.

-jJ


More information about the Python-ideas mailing list