[Python-ideas] Why does += trigger UnboundLocalError?
Terry Reedy
tjreedy at udel.edu
Thu Jun 2 00:56:52 CEST 2011
On 6/1/2011 1:41 PM, Terry Reedy wrote:
> On 6/1/2011 12:52 AM, Carl M. Johnson wrote:
>
>> So, my proposal is that += by itself should not cause x to be considered
>> a local variable.
> While I do understand your point, I also value uniformity.
> -1
There is another problem I had not thought of before. Right now, Python
has (always had) a simple rule: code in a function CANNOT rebind names
in outer scopes unless the function has a global or nonlocal
declaration. This simple, uniform rule benefits not only the interpreter
but human readers. It should not be broken.
def f():
'doc for f'
def g():
'docstring of g'
<body of g>
<body of f>
If g is the only nested function and the body of g does not have a
nonlocal declaration (which OUGHT to be at the top if present), then a
reader or maintainer of f knows (without reading g in detail) that
nothing other that <body of f> can rebind f's locals.
--
Terry Jan Reedy
More information about the Python-ideas
mailing list