Reputation: 28014
I have a class
class Resource:
__init__(self):
self.resource = ...
__enter__(self):
#can fail, such as file open returning error, memory allocation fail, or any more complicated failure
__exit__(self,*args):
...
Now I want
with Resource() as r:
r.do_stuff()
But if r
has failed to __enter__()
successfully, this fails.
What is the correct, pythonic way of handling this?
I didn't want to use some is_allocated_correctly
like so
with Resource() as r:
if r.is_allocated_correctly():
r.do_stuff()
as it breaks the point of the with statement.
Please give me some idea what to do here.
Upvotes: 0
Views: 43
Reputation: 24153
The purpose of the with
statement is correctly de-allocate resources or reset state after the block has finished.
If you can't enter the context block without an error, that needs handling outside of the with statement.
Surround the whole thing with a try/except
:
try:
with Resource() as r:
r.do_stuff()
except ResourceException as error:
handle_error(error)
Or if there's nothing you can do about the error, just let it pass:
with Resource() as r:
r.do_stuff()
Upvotes: 2