Conditionally skipping the contents of a with-statement

Diez B. Roggisch deets at nospam.web.de
Fri Aug 21 17:02:08 CEST 2009


tsuraan schrieb:
> 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?

No. The only way would be something like this:

with Fork() as is_child:
     if is_child:
        ...



Diez



More information about the Python-list mailing list