Conditionally skipping the contents of a with-statement

tsuraan tsuraan at gmail.com
Fri Aug 21 10:50:01 EDT 2009


I'd like to write a Fork class to wrap os.fork that allows something like this:

with Fork():
  # to child stuff, end of block will automatically os._exit()
# parent stuff goes here

This would require (I think) that the __enter__ method of my Fork
class to be able to return a value or raise an exception indicating
that the block should not be run.  It looks like, from PEP343, any
exception thrown in the __enter__ isn't handled by with, and my basic
tests confirm this.  I could have __enter__ raise a custom exception
and wrap the entire with statement in a try/except block, but that
sort of defeats the purpose of the with statement.  Is there a clean
way for the context manager to signal that the execution of the block
should be skipped altogether?



More information about the Python-list mailing list