Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

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.


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.


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).

See http://www.python.org/dev/peps/pep-3104/




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: