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()
           return self

       def __exit__(self, exc_type, exc_val, exc_tb):

   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.


J. D. Bartlett