What are python closures realy like?

Roy Smith roy at panix.com
Tue Dec 12 09:14:55 EST 2006


John Nagle <nagle at animats.com> wrote:
>     Most of the examples given here are kind of silly, but closures have
> real uses.  I used one today in Javascript because I was writing an
> AJAX application, and I was using an API, the standard XMLHttpRequestObject,
> which required a callback function with no arguments.  A closure allowed
> the code to pass relevant information with the callback function, which
> would be called when a request to the server completed.  A global
> variable wouldn't have worked, because multiple instances of the object
> making the callback are possible.

As another example, from a large C++ project I'm currently working on, we 
use closures in many places to push actions onto queues.

One kind of queue we have is a timed queue.  You push a closure and a time 
onto it, and it executes the closure at the appointed time.  Another kind 
of queue is for inter-thread communication.  You push a closure onto a 
thread's input queue when you want it to do something.  The thread just 
keeps popping closures off the other end of the queue and executing them.

Think of a closure as a way of saying "do this".  You can say, "At 5:00, do 
this", or "Do this as soon as you get a chance".

# pseudocode
class husband (spouse):
   def pickUpGroceries():
      etc
   def addToQueue():
      etc

c = makeClosure (husband.pickUpGroceries, [milk, eggs, bread])
h = husband()
h.addToQueue (c)



More information about the Python-list mailing list