contextlib.closing(thing)
Return a context manager that closes thing upon completion of the block. This is basically equivalent to:
1 2 3 4 5 6 7 8 | from contextlib import contextmanager @contextmanager def closing(thing): try : yield thing finally: thing.close() |
And lets you write code like this:
1 2 3 4 5 6 | from contextlib import closing from urllib.request import urlopen for line in page: print(line) |
without needing to explicitly close page
. Even if an error occurs, page.close()
will be called when the with
block is exited.
Please login to continue.