So what's said here is :
from contextlib import contextmanager
@contextmanager
def custom_open(filename):
f = open(filename)
yield f
f.close()
with custom_open('file') as f:
contents = f.read()
But as far as I undestand, we shoud wrap the yield into a try: block with the close in the finally:, otherwise a exception might allow leaving the with block without calling close. I might do a PR for this, but I wanted to check with someone if there was a reason the code was shown this way and/or if I was mistaken altogether...
So what's said here is :
But as far as I undestand, we shoud wrap the
yieldinto atry:block with theclosein thefinally:, otherwise a exception might allow leaving thewithblock without callingclose. I might do a PR for this, but I wanted to check with someone if there was a reason the code was shown this way and/or if I was mistaken altogether...