closure = decorator?

Roy Smith roy at panix.com
Thu Oct 10 20:04:23 EDT 2013


In article <m2a9ihxf3a.fsf at cochabamba.vanoostrum.org>,
 Piet van Oostrum <piet at vanoostrum.org> wrote:

> I usually say that a closure is a package, containing a function with
> some additional data it needs. The data usually is in the form of name
> bindings.

That's pretty close to the way I think about it.  The way it was 
originally described to me is, "A closure is a function bundled up with 
it's arguments".

To make a real-life analogy, let's say you're modeling a parking garage.  
I want to be able to walk up to the attendant and say, "Please bring my 
car around front at 5 O'Clock.  It's that one" (pointing to the slightly 
dented green Ford in spot 37).  So, you've got a class:

class DeliveryRequest:
   def __init__(self, spot, time):
      self.spot = spot
      self.time = time

Now, over the course of the day, the garage attendants shuffle cars 
around to make room and retrieve vehicles that packed in the back.  
Comes 5 O'Clock, what vehicle do you want the attendant to deliver to 
the front?  The one that was in spot 37 at the time you made the 
request, or the one that's in spot 37 at 5 O'Clock?

Unless you want somebody else's car (perhaps you'd like something better 
than a slightly dented Ford), you want the attendant to capture the 
current state of spot 37 and remember that until 5 O'Clock when it's 
time to go get the car, no matter where it happens to be right now.

That's a closure.



More information about the Python-list mailing list