Conditionally skipping the contents of a with-statement

T

tsuraan

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?
 
D

Diez B. Roggisch

tsuraan said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,199
Messages
2,571,045
Members
47,643
Latest member
ashutoshjha_1101

Latest Threads

Top