Author olau
Recipients olau
Date 2009-11-06.19:23:14
SpamBayes Score 7.29306e-13
Marked as misclassified No
Message-id <1257535397.32.0.778843860173.issue7276@psf.upfronthosting.co.za>
In-reply-to
Content
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.
History
Date User Action Args
2009-11-06 19:23:17olausetrecipients: + olau
2009-11-06 19:23:17olausetmessageid: <1257535397.32.0.778843860173.issue7276@psf.upfronthosting.co.za>
2009-11-06 19:23:15olaulinkissue7276 messages
2009-11-06 19:23:14olaucreate