Message94994
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. |
|
Date |
User |
Action |
Args |
2009-11-06 19:23:17 | olau | set | recipients:
+ olau |
2009-11-06 19:23:17 | olau | set | messageid: <1257535397.32.0.778843860173.issue7276@psf.upfronthosting.co.za> |
2009-11-06 19:23:15 | olau | link | issue7276 messages |
2009-11-06 19:23:14 | olau | create | |
|