pre-PEP: Simple Thunks
Ron_Adam
radam2_ at _tampabay.rr.com
Sat Apr 16 16:18:58 EDT 2005
On Fri, 15 Apr 2005 16:44:58 -0700, Brian Sabbey
<sabbey at u.washington.edu> wrote:
>
>Simple Thunks
>-------------
>
>Thunks are, as far as this PEP is concerned, anonymous functions that
>blend into their environment. They can be used in ways similar to code
>blocks in Ruby or Smalltalk. One specific use of thunks is as a way to
>abstract acquire/release code. Another use is as a complement to
>generators.
I'm not familiar with Ruby or Smalltalk. Could you explain this
without referring to them?
>A Set of Examples
>=================
>
>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.
>
>def f(thunk):
> before()
> thunk()
> after()
>
>do f():
> stuff()
>
>The above code has the same effect as:
>
>before()
>stuff()
>after()
You can already do this, this way.
>>> def f(thunk):
... before()
... thunk()
... after()
...
>>> def before():
... print 'before'
...
>>> def after():
... print 'after'
...
>>> def stuff():
... print 'stuff'
...
>>> def morestuff():
... print 'morestuff'
...
>>> f(stuff)
before
stuff
after
>>> f(morestuff)
before
morestuff
after
>>>
This works with arguments also.
>Other arguments to 'f' get placed after the thunk:
>
>def f(thunk, a, b):
> # a == 27, b == 28
> before()
> thunk()
> after()
>
>do f(27, 28):
> stuff()
Can you explain what 'do' does better?
Why is the 'do' form better than just the straight function call?
f(stuff, 27, 28)
The main difference I see is the call to stuff is implied in the
thunk, something I dislike in decorators. In decorators, it works
that way do to the way the functions get evaluated. Why is it needed
here?
When I see 'do', it reminds me of 'do loops'. That is 'Do' involves
some sort of flow control. I gather you mean it as do items in a
list, but with the capability to substitute the named function. Is
this correct?
Cheers,
Ron
More information about the Python-list
mailing list