[Python-ideas] Possible PEP 380 tweak (original) (raw)

Ron Adam rrr at ronadam.com
Wed Oct 27 17:01:00 CEST 2010


On 10/25/2010 10:25 PM, Guido van Rossum wrote:

By the way, here's how to emulate the value-returning-close() on a generator, assuming the generator uses raise StopIteration(x) to mean return x:

def gclose(gen): try: gen.throw(GeneratorExit) except StopIteration, err: if err.args: return err.args[0] except GeneratorExit: pass return None I like this because it's fairly straightforward (except for the detail of having to also catch GeneratorExit). In fact it would be a really simple change to genclose() in genobject.c -- the only change needed there would be to return err.args[0]. I like small evolutionary improvements to APIs.

Here's an interesting idea...

It looks like a common case for consumer co-functions is they need to be started and then closed, so I'm wondering if we can make these work context managers? That may be a way to reduce the need for the try/except blocks inside the generators.

 with my_cofunction(args) as c:
    ... use c

Regards, Ron



More information about the Python-ideas mailing list