[Python-Dev] PEP 340: Non-looping version (aka PEP 310 redux)

Steven Bethard steven.bethard at gmail.com
Thu May 5 19:23:20 CEST 2005

On 5/5/05, Nick Coghlan <ncoghlan at iinet.net.au> wrote:
> The discussion on the meaning of break when nesting a PEP 340 block statement
> inside a for loop has given me some real reasons to prefer PEP 310's single pass
> semantics for user defined statements (more on that at the end). The suggestion
> below is my latest attempt at combining the ideas of the two PEP's.
> * An iterable factory (such as a generator, or class with an __iter__ method) is
> converted to a block statement factory

I like the non-looping proposal a lot, but I'd still prefer that
iterators were not usable as statements.  As I understand it, the main
motivation for wanting iterators to be usable as statements is that
generators provide a very simple way of creating iterators, and we'd
like to have an equally simple way of creating statments.  The
simplicity of generators is that using a "yield" statement inside a
"def" statement magically modifies the function so that it returns
"iterator" objects.  I'd like to see a parallel for block-statements,
so that using an "XXX" statement inside a "def" statement magically
modifies the function so that it returns "statement" objects.

To illustrate my point, I'm going to assume a no-keyword syntax for
calling statement objects and I'm going to steal your "stmt" keyword
to replace "yield". So, for example, to create the "opening" statement
from PEP 340, you would write it almost exactly the same:

    def opening(filename, mode="r"):
        f = open(filename, mode)
            stmt f

This would create a generator-like object that instead of providing
__iter__() and next() methods, provides __enter__() and __exit__()
methods.  It could then be called like:

    opening("temp.txt") as f:
        for line in f:
            print line

I like this for a few reasons:
* statement-generators (or whatever you want to call them) are just as
easy to declare as normal generators are
* try/finally statements around a "yield" would still be invalid
syntax, as generators can't generally guarantee proper finalization
* statement objects can't be accidentally used in for-loops; they
don't have __iter__() or next() methods
* statement objects can be clearly documented separately from iterator
objects; there would be no need for them to refer to each other

I don't know the generator implementation very well, but I would think
that statement-generators could share almost all the code of normal
generators by simply changing the name of a slot or two and adding the
__exit__ code already proposed by PEP 340.

You can wordify anything if you just verb it.
        --- Bucky Katt, Get Fuzzy

More information about the Python-Dev mailing list