[Python-Dev] Anonymous blocks: Thunks or iterators?

Greg Ewing greg.ewing at canterbury.ac.nz
Thu Apr 28 10:42:26 CEST 2005


Elegant as the idea behind PEP 340 is, I can't shake
the feeling that it's an abuse of generators. It seems
to go to a lot of trouble and complication so you
can write a generator and pretend it's a function
taking a block argument.

I'd like to reconsider a thunk implementation. It
would be a lot simpler, doing just what is required
without any jiggery pokery with exceptions and
break/continue/return statements. It would be easy
to explain what it does and why it's useful.

Are there any objective reasons to prefer a generator
implementation over a thunk implementation? If
for-loops had been implemented with thunks, we might
never have created generators. But generators have
turned out to be more powerful, because you can
have more than one of them on the go at once. Is
there a use for that capability here?

I can think of one possible use. Suppose you want
to acquire multiple resources; one way would be to
nest block-statements, like

    block opening(file1) as f:
       block opening(file2) as g:
          ...

If you have a lot of resources to acquire, the nesting
could get very deep. But with the generator implementation,
you could do something like

    block iterzip(opening(file1), opening(file2)) as f, g:
       ...

provided iterzip were modified to broadcast __next__
arguments to its elements appropriately. You couldn't
do this sort of thing with a thunk implementation.

On the other hand, a thunk implementation has the
potential to easily handle multiple block arguments, if
a suitable syntax could ever be devised. It's hard
to see how that could be done in a general way with
the generator implementation.

[BTW, I've just discovered we're not the only people
with numbered things called PEPs. I typed "PEP 340"
into Google and got "PEP 340: Prevention and Care of
Athletic Injuries"!]

Greg



More information about the Python-Dev mailing list