Python - Exception seems to be skipping out of with block -
this question has answer here:
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 eithernext()
orthrow()
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
Post a Comment