[Python-Dev] generators and with

dustin at v.igoro.us dustin at v.igoro.us
Sun May 13 17:33:45 CEST 2007


On Sun, May 13, 2007 at 04:56:15PM +0200, tomer filiba wrote:
>    why not add __enter__ and __exit__ to generator objects?
>    it's really a trivial addition: __enter__ returns self, __exit__ calls
>    close().
>    it would be used to ensure close() is called when the generator is
>    disposed,
>    instead of doing that manually. typical usage would be:
>    with mygenerator() as g:
>        g.next()
>        bar = g.send("foo")
>    -tomer

A better example may help to make your case.  Would this do?

    with mygeneratorfn() as g:
        x = get_datum()
        while g.send(x):
            x = get_next(x)

The idea then is that you can't just use a 'for' loop (which will call
close() itself, IIRC) because you want access to the generator itself,
not just the return values from g.next().

I wouldn't have a problem with this proposal, but I consider the snippet
above to be fairly obscure Python already; the requirement to call
g.close() is not a great burden on someone capable of using g.send() et
al.

Dustin


More information about the Python-Dev mailing list