pre-PEP: Simple Thunks

Leif K-Brooks eurleif at ecritters.biz
Fri Apr 15 20:56:00 EDT 2005


Brian Sabbey wrote:
> Thunk statements contain a new keyword, 'do', as in the example below. 
> The body of the thunk is the suite in the 'do' statement; it gets passed 
> to the function appearing next to 'do'. The thunk gets inserted as the 
> first argument to the function, reminiscent of the way 'self' is 
> inserted as the first argument to methods.

It would probably make more sense to pass the thunk as the last 
argument, not as the first. That would make it easier to create 
functions with optional thunks, as in:

def print_nums(start, end, thunk=None):
     for num in xrange(start, end+1):
         if thunk is not None:
             num = thunk(num)
         print num

print_nums(1, 3) # prints 1, 2, 3

do num print_nums(1, 3): # prints 2, 4, 6
     continue num * 2

> Because thunks blend into their environment, a thunk cannot be used 
> after its surrounding 'do' statement has finished

Why? Ordinary functions don't have that restriction:

 >>> def foo():
...     x = 1
...     def bar():
...         return x
...     return bar
...
 >>> foo()()
1



More information about the Python-list mailing list