
report at bugs
Nov 6, 2009, 11:23 AM
Post #1 of 4
(319 views)
Permalink
|
|
[issue7276] UnboundLocalError scoping problem with nested functions
|
|
New submission from Ole Laursen <olau [at] iola>: 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> <http://bugs.python.org/issue7276> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: http://mail.python.org/mailman/options/python-bugs-list/list-python-bugs%40lists.gossamer-threads.com
|