On 5/4/05, Nick Coghlan <[EMAIL PROTECTED]> wrote:
> With single-pass semantics, an iterator used in a block statement would have
> it's .next() method called exactly once, and it's __exit__ method called 
> exactly
> once if the call to .next() does not raise StopIteration. And there's no need 
> to
> mess with the meaning of break, return or continue - they behave as usual,
> affecting the surrounding scope rather than the block statement.
> 
> The only new thing needed is an __exit__ method on generators (and the block
> syntax itself, of course).

Makes me wonder if we shouldn't just return to the __enter__() and
__exit__() names of PEP 310[1] where for a generator __enter__() is
just an alias for next().  We could even require Phillip J. Eby's
"blockgenerator" decorator to rename next() to __enter__(), and add
the appropriate __exit__() method.  Something like:

    class blockgen(object):
        def __init__(self, gen):
            self.gen = gen
        def __enter__(self):
            self.gen.next()
        def __exit__(self):
            # cause finally blocks to be executed
    
    def blockgenerator(genfunc):
        def getblockgen(*args, **kwargs):
            return blockgen(genfunc(*args, **kwargs))
        return getblockgen

to be used like:

    @blockgenerator
    def locking(lock):
        lock.acquire()
        try:
            yield
        finally:
            lock.release()

'Course, it might be even nicer if try/finally around a yield could
only be used with block generators...  To get a syntax error, we'd
have to replace the decorator with a new syntax, e.g. Tim Delaney's
"resource" instead of "def" syntax or maybe using something like
"blockyield" or "resourceyield" instead of "yield" (though these are
probably too long)...

Steve

[1]http://www.python.org/peps/pep-0310.html
-- 
You can wordify anything if you just verb it.
        --- Bucky Katt, Get Fuzzy
_______________________________________________
Python-Dev mailing list
Python-Dev@python.org
http://mail.python.org/mailman/listinfo/python-dev
Unsubscribe: 
http://mail.python.org/mailman/options/python-dev/archive%40mail-archive.com

Reply via email to