[Python-Dev] nonlocal keyword in 2.x?

Fernando Perez fperez.net at gmail.com
Fri Oct 23 08:07:41 CEST 2009

On Thu, 22 Oct 2009 12:32:37 -0300, Fabio Zadrozny wrote:

> Just as a note, the nonlocal there is not a requirement...
> You can just create a mutable object there and change that object (so,
> you don't need to actually rebind the object in the outer scope).
> E.g.: instead of creating a float in the context, create a list with a
> single float and change the float in the list (maybe the nonlocal would
> be nicer, but it's certainly still usable)

Yup, that's what I meant by 'some slightly ugly solutions' in this note:


in the thread that spawned those notes.  nonlocal allows for this pattern 
to work without the ugliness of writing code like:

s = [s]

def foo():
  s[0] += 1

s = s[0]

just to be able to 'change s' inside the foo() scope.

I felt this was both obvious and ugly enough not to warrant too much 
explicit mention, but I probably should have left it there for the sake of 
completeness.  Thanks for the feedback.



ps - the above shouldn't be taken as either pro or con on the idea of 
nonlocal in 2.x, just a clarification on why I didn't add the mutable 
container trick to the original notes.

More information about the Python-Dev mailing list