Replies: 2 comments
-
… but (luckily in this case) that's not typically how context managers work. there are 2 steps involved:
these are often on the same line, but it's actually the first step that can fail. in the case of opening files, with the steps split over 2 statements: fp = open(...) # this may raise (e.g. not found, permission problem, ...)
with fp: # __enter__ called here, will not raise
fp.read(...) # or sth else, which may also raise
# __exit__ called here, may raise if .close() fails somehow (unlikely!) in practice i think the |
Beta Was this translation helpful? Give feedback.
0 replies
-
@seanbone, can you clarify a bit more? What specifically are you trying to achieve? |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I'm writing a class which represents access to a file. I want to make sure that the file handle is properly cleaned up whenever the object is deallocated; including in case of an exception.
Normally (in C++ or Rust) I'd add logic to the class' destructor to close the file. In Python however, there is no good way to do this, because
__del__
isn't actually a destructor and Python doesn't support RAII.Instead the recommended pattern is to write a Context Manager class using
__enter__
and__exit__
. The issue is that this is predicated on using exceptions for error handling:__enter__
is expected to throw if it encounters an issue, and the only way to early-exit awith
block is by raising an exception.I can write an
__enter__
which returns aResult
, the thing is that when I write something like this:...one would expect
f
to be the object, not aResult
.Is this the best we can aim for? Any suggestions on how resource handling could be done both robustly and elegantly using
Result
?Beta Was this translation helpful? Give feedback.
All reactions