
On Mon, Sep 26, 2011 at 2:56 AM, Greg Ewing <greg.ewing@canterbury.ac.nz> wrote:
- A 'nonlocal' declaration makes it refer to some namespace in between local and module-level (there may be more than one of these, so I wouldn't say that there are only 4 namespaces).
Now, while the *value* of your proposed new kind of variable would be stored as part of the function's closure, its *name* would be part of the function's *local* namespace. Consider this:
i = 88
def f(): nonlocal i = 17 print i
def g(): nonlocal i = 42 print i
f() g() print i
I'm assuming you intend that the two i's here would have nothing to do with each other, or with the i in the enclosing scope, so that the output from this would be
17 42 88
rather than
42 42 42
So, your proposed use of 'nonlocal' would actually be declaring a name to be *local*. That strikes me as weird and perverse.
Ah, but it *wouldn't* be local, that's the point - it would be stored on the function rather than on the frame, and hence be shared across invocations. Change your example function to this so it actually modifies the name binding, and it becomes clear that this is *not* a local variable declaration: i = 88 def f(): nonlocal i from 17 print(i) i += 1
f() 17 f() 18
It would work exactly as if we had introduced a containing scope as a closure: def outer(): i = 17 def f(): nonlocal i print(i) i += 1 return f
f = outer() f() 17 f() 18
The *only* thing that would change is the way the closure reference would be initialised - it would happen as part of the function definition (just like default arguments) rather than needing the developer to write the outer scope explicitly just to initialise the closure references. Cheers, Nick. -- Nick Coghlan | ncoghlan@gmail.com | Brisbane, Australia