On Wed, Jan 20, 2016 at 4:10 PM, Steven D'Aprano <steve@pearwood.info> wrote:
I'm just tossing the "static block" idea out for discussion, but if you
want a justification here are two differences between capture/static
and global/nonlocal which suggest they aren't that similar and so we
shouldn't feel obliged to use the same syntax.

(1) global and nonlocal operate on *names*, not values. E.g. after
"global x", x refers to a name in the global scope, not the local scope.

But "capture"/"static" doesn't affect the name, or the scope that x
belongs to. x is still a local, it just gets pre-initialised to the
value of x in the enclosing scope. That makes it more of a binding
operation or assignment than a declaration.

(2) If we limit this to only capturing the same name, then we can only
write (say) "static x", and that does look like a declaration. But maybe
we want to allow the local name to differ from the global name:

    static x = y

or even arbitrary expressions on the right:

    static x = x + 1

Now that starts to look more like it should be in a block of code,
especially if you have a lot of them:

    static x = x + 1
    static len = len
    static data = open("data.txt").read()

versus:

    static:
        x = x + 1
        len = len
        data = open("data.txt").read()


I acknowledge that this goes beyond what the OP asked for, and I think
that YAGNI is a reasonable response to the static block idea. I'm not
going to champion it any further unless there's a bunch of interest from
others.

Yeah, your arguments why it's different from global/nonlocal are reasonable, but the question remains whether we really need all that functionality. IIRC C++ lambdas only allow capturing a variable's value, not an expression's.

So we should ask ourselves first: if we *only* had some directive that captures some variables' values, essentially like the len=len argument trick but without affecting the signature (e.g. just "static x, y, z"), how much of the current pain would be addressed, and how much would remain?
 
(I'm saving my energy for Eiffel-like require/ensure blocks
*wink*).

Now you're making me curious.

--
--Guido van Rossum (python.org/~guido)