Python - Exception seems to be skipping out of with block -


here relevant pieces of code:

    @contextlib.contextmanager     def make_temp_dir():       temp_dir = tempfile.mkdtemp()       yield temp_dir       shutil.rmtree(temp_dir)      make_temp_dir(listing_id) tmpdir:       pass       # in here throws exception gets caught higher 

ok, writing out, understand what's happening. exit method in contextmanager i'm creating decorator is running doesn't, of course, return flow generator.

so how should doing this?

what happens here following:

  • on __enter__(), generator started. yields taken return value of __enter__().
  • on __exit__(), generator resumed, either in normal way or injecting exception. relevant code in $pythonroot/contextlib.py can see either next() or throw() called on generator.

if throw() called on generator, exception raised inside left last time, i. e. yield expression raises exception then.

thus, have enclose yield in try: statement. then, you'll able exception.

if fail so, generator raise exception without doing anything.

you want

@contextlib.contextmanager def make_temp_dir():     temp_dir = tempfile.mkdtemp()     try:         yield temp_dir     finally:         shutil.rmtree(temp_dir) 

Comments

Popular posts from this blog

C# random value from dictionary and tuple -

cgi - How do I interpret URLs without extension as files rather than missing directories in nginx? -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -