[Python-Dev] code blocks using 'for' loops and generators

Brian Sabbey sabbey at u.washington.edu
Mon Mar 14 01:21:19 CET 2005

On Mon, 14 Mar 2005, Greg Ewing wrote:
> Brian Sabbey wrote:
>> The problem with creating a new mechanism is that sometimes you will want 
>> to loop.  For example, reading a bunch of items from a shared resource, 
>> modifying them, and sending them back.  A new, non-looping mechanism will 
>> not be adequate for this because it cannot loop,
> If there is a mechanism for passing a code block as
> a thunk to an arbitrary function, the function is
> free to loop or not as it sees fit. I'd just prefer
> the spelling of it didn't force you to make it
> look like it's looping when it's not.

I think you're right.  How about something like below?  In the same way 
that "self" is passed "behind the scenes" as the first argument, so can 
the thunk be.  (Many ideas taken from around [1])

def stopwatch(thunk):
     t = time.time()
     return t - time.time()

with stopwatch() result dt:
print 'it took', dt, 'seconds to compute'


def pickled_file(thunk, name):
     f = open(name)
     new_data = thunk(pickle.load(f))
     f = open(name, 'w')
     pickle.dump(new_data, f)

with greetings from pickled_file('greetings.pickle'):
     value greetings

[1] http://mail.python.org/pipermail/python-dev/2003-February/032732.html


More information about the Python-Dev mailing list