This post originated from an RSS feed registered with Python Buzz
by maxim khesin.
Original Post: python closures piss me off (sorry)
Feed Title: python and the web
Feed URL: http://feeds.feedburner.com/PythonAndTheWeb
Feed Description: blog dedicated to python and the networks we live in
I've been writing a play program on the train to-fro work. One of the parts was a parser function, which tend to be longish and internally repetitive (or at lease my version is). Sorry, the code is too long to post out of context. So I wrote an inner helper function for the boilerplate stuff and was.
An example-only equivalent would be something like this:
def foo(): ... a = 'a' ... def bar(): ....... if a: ....... a = 'b' ... bar() ... print a
This seemed like a fine idea, but I kept getting UnboundLocalError, because I was assigning to the variable! This surprised me quite a bit until I got home an found this (excellent, BTW) explaination.
I now grokked the error, but the final ansewer seems to be that closures in Python will not work intuitively in certain cases.
As the above post mentions the problem is very similar to the one that was solved by the 'global' keyword. Not having the equivalend of 'global' for nested scopes is at the very least not symmetrical. While the ultimate solution mentioned (having a different assignment operator that does not bind a new variable name) is a sweet long-shot, especially since it was not chosen to deal with the globals problem, I think at the very least adding a keyword specifying that a the variable name should be looked up rather than created would be a descent and explicit solution.