Closures in python

JCM joshway_without_spam at myway.com
Thu Sep 18 09:19:58 EDT 2003


Hallvard B Furuseth <h.b.furuseth(nospam)@usit.uio(nospam).no> wrote:
> 'closure' is a much-abused word.
> This is a closure over foo's x variable:

> def foo():
>   x = 3
>   def bar():
>     x += 1
>     return x
>   return bar

> f = foo()
> print f()  # print 4
> g = foo()
> print f()  # print 5
> print g()  # print 4

> ...or it would be, if it worked.

Python does have closures; the trouble is you can't rebind variables
defined in arbitrary scopes--you can only rebind locals and globals.
So you need some indirection for it to work:

  >>> def foo():
  ...   x = [3]
  ...   def bar():
  ...     x[0] += 1
  ...     return x[0]
  ...   return bar
  ... 
  >>> f = foo()
  >>> f()
  4
  >>> g = foo()
  >>> f()
  5
  >>> g()
  4

This is actually one of my biggest complaints about Python.  I'd like
syntactic disambiguation between definition and assignment in order to
have control over which scope you're assigning into.




More information about the Python-list mailing list