[Python-ideas] Yielding through context managers

Jan Kaliszewski zuo at chopin.edu.pl
Fri Mar 30 21:39:38 CEST 2012


> >class cd(object):
> > def __init__(self, path):
> > self.inner_path = path
> >
> > def __enter__(self):
> > self.outer_path = os.getcwd()
> > os.chdir(self.inner_path)
> >
> > def __exit__(self, exc_type, exc_val, exc_tb):
> > os.chdir(self.outer_path)
> >
> > def __yield__(self):
> > self.inner_path = os.getcwd()
> > os.chdir(self.outer_path)
> >
> > def __send__(self):
> > self.outer_path = os.getcwd()
> > os.chdir(self.inner_path)
[snip]
> >def my_generator(path):
> > with cd(path):
> > yield do_something()
> > do_something_else()

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
 ...
Cheers.
*j


More information about the Python-ideas mailing list

AltStyle によって変換されたページ (->オリジナル) /