[New-bugs-announce] [issue7276] UnboundLocalError scoping problem with nested functions

Ole Laursen report at bugs.python.org
Fri Nov 6 20:23:17 CET 2009


New submission from Ole Laursen <olau at iola.dk>:

This works:

def outer(name):
    tmp = name
    def inner():
        print(tmp)
    return inner

outer("foo") # prints "foo"

While the same code with one extra line (setting tmp after printing) 
fails

def outer(name):
    tmp = name
    def inner():
        print(tmp)
        tmp = "hello"
    return inner

outer("foo")()

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in inner
UnboundLocalError: local variable 'tmp' referenced before assignment

and the following works

def outer(name):
    tmp = name
    def inner():
        tmp = "hello"
        print(tmp)
    return inner

outer("foo")() # prints "hello"

Now, I understand there's an interesting issue of assignment binding to 
the inner-most scope. So tmp = "hello" is binding a new variable, not 
changing the outermost tmp. But I should still be able to read tmp, 
right? It looks like some kind of optimizer error.


For the record, this pattern came up in a decorator like this

def deco(x = None):
    def inner(fn):
         if not x:
             x = somedefaultvalue
    
    return inner

which gives the same UnboundLocalError error.

----------
messages: 94994
nosy: olau
severity: normal
status: open
title: UnboundLocalError scoping problem with nested functions
type: compile error

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue7276>
_______________________________________


More information about the New-bugs-announce mailing list