Nested scopes, and augmented assignment

Tim N. van der Leeuw tim.leeuwvander at nl.unisys.com
Tue Jul 4 08:07:18 EDT 2006


Hi,

The following might be documented somewhere, but it hit me unexpectedly
and I couldn't exactly find this in the manual either.

Problem is, that I cannot use augmented assignment operators in a
nested scope, on variables from the outer scope:

PythonWin 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit
(Intel)] on win32.
Portions Copyright 1994-2004 Mark Hammond (mhammond at skippinet.com.au) -
see 'Help/About PythonWin' for further copyright information.
>>> def foo():
... 	def nestedfunc(bar):
... 		print bar, ';', localvar
... 		localvar += 1
... 	localvar=0
... 	nestedfunc('bar')
...
>>> foo()
bar =Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
  File "<interactive input>", line 6, in foo
  File "<interactive input>", line 3, in nestedfunc
UnboundLocalError: local variable 'localvar' referenced before
assignment
>>>

This is entirely counter-intuitive to me, and searching the manual for
nested scoping rules and for augmented assignment rules, I still feel
that I couldn't have predicted this from the docs.

Is this an implementation artifact, bug, or should it really just
follow logically from the language definition?

Regards,

--Tim




More information about the Python-list mailing list