Re:How To Let People Know You're A Bad Python Programmer
by abstractbill on Friday August 28, 2009 @01:47PM
(#791858)
They don't seem to work very well:
>>> def foo():
... blah = 42
... def wibble():
... print "blah is " + blah
... wibble()
...
>>> foo()
blah is 42
Great! Looks like we have real closures! >>> def foo():
... blah = 42
... def wibble():
... blah += 1
... wibble()
... print "blah is " + blah
...
>>> foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in foo
File "<stdin>", line 4, in wibble
UnboundLocalError: local variable 'blah' referenced before assignment
Oh. Maybe not.
Re:How To Let People Know You're A Bad Python Programmer
by arohner on Friday August 28, 2009 @02:54PM
(#792005)
That's a scoping problem, not a closure problem. The issue in this example is that python doesn't have true lexical scope. It has three scopes: function level, class level, file level. If you wrote "global blah", it would look at file level, not the next function level.
I agree it's broken, but it's a different flaw than the closure problem.
Re:How To Let People Know You're A Bad Python Programmer
by Cald on Friday August 28, 2009 @03:09PM
(#792035)
I think the nonlocal keyword would make your second example work as you expect (but I can't test it as I don't have Python 3.0 installed here).
Re:How To Let People Know You're A Bad Python Programmer
by grunt on Friday August 28, 2009 @01:56PM
(#791873)
Only since Python 3000, with the addition of the "nonlocal" declaration, can python claim to have closures. And yes, Python does also have "first-class functions"--in the same way that C has first-class functions. It's the "anonymous" part that it has difficulty with.
Re:How To Let People Know You're A Bad Python Programmer
by ubernostrum on Friday August 28, 2009 @03:00PM
(#792019)
Glad to know I can add you to my list of people who believe that Haskell does not (and by definition cannot) have closures.
Which Python are you talking about? The language I use has had closures and first-class functions for years.