[Python-ideas] Yielding through context managers

Joshua Bartlett josh at bartletts.id.au
Sat Mar 31 03:45:14 CEST 2012


> Interesting idea, though doing this with present Python does not seem to
> be very painful:
>
>    class cd(object):
>
>        def __init__(self, path):
>            self.inner_path = path
>
>        def __enter__(self):
>            self.outer_path = os.getcwd()
>            os.chdir(self.inner_path)
>            return self
>
>        def __exit__(self, exc_type, exc_val, exc_tb):
>            os.chdir(self.outer_path)
>
>    def my_generator(path):
>        with cd(path) as context:
>            output = do_something()
>            with cd(context.outer_path):
>                yield output
>            ...
>

Yes, that's possible, although as the context manager gets more complicated
(e.g. modifying os.environ as well as working directory, I'd currently
start using something like this:

def my_generator(arg):
    with context_manager(arg) as context:
        output = do_something()
        with context.undo():
            yield output
        ...

But nevertheless adding __yield__ and __send__ (or equivalent) to context
managers means that the author of the context manager can make sure that
it's free of unintended side effects, rather than relying on the user to be
careful as in the examples above.

Cheers,

J. D. Bartlett
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20120331/fdda52ee/attachment.html>


More information about the Python-ideas mailing list