[Python-Dev] PEP 340 - For loop cleanup, and feature separation

Delaney, Timothy C (Timothy) tdelaney at avaya.com
Fri May 6 05:58:48 CEST 2005


Greg Ewing wrote:

> I'm still bothered by the idea of for-loops not participating
> in the new generator finalization protocol.

I agree - that's always been nagging at me too.

The problem with it is that then you either:

1. Have a guarantee that an iterator will be exhausted when the for loop
exits (as per block statements);

OR

2. Rely on garbage collection (reference counting, etc) to ensure
finalisation.

Personally, I'm of the opinion that we should make a significant break
(no pun intended ;) and have for-loops attempt to ensure that iterators
are exhausted. An iterator could be specifically designed to prevent
that if needed, but in the vast majority of cases an iterator is never
used after the for-loop.

An example of an iterator that was specifically designed to continue
working after its initial for-loop would be::

    def gen():
        try:
            setup1()

            try:
                yield 1
            finally:
                cleanup1()

        except StopIteration:
            pass

        setup2()

        try:
            yield 2
        finally:
            cleanup2()

This allows cleanup, but then continued usage.

> So I think that, in the interests of least surprise,
> for-loops should provide the same finalization promises
> as block statements.

Agreed.

> If that is done, it becomes easier to decide whether
> the block statement should loop. The answer is probably
> no: If you're writing a loop, you use a for-statement;
> if you're not, you use a block-statement. This helps
> to clearly differentiate the two, and provide
> justification for having two statements.

Agreed.

> I'm also starting to like the idea of having a
> completely separate protocol for block-statements

+1

> and an adaptor of some kind for using generators to
> implement them.

My preference would be direct syntactic support...

Tim Delaney


More information about the Python-Dev mailing list