15 Contextlib Closing Thing
15 Contextlib Closing Thing
closing(thing)
The contextlib module comes with some other handy utilities. The first one is
the closing class which will close the thing upon the completion of code block.
The Python documentation gives an example that’s similar to the following
one:
@contextmanager
def closing(db):
try:
yield db.conn()
finally:
db.close()
In this example, we open a url page but wrap it with our closing class. This
will cause the handle to the web page to be closed once we fall out of the with
statement’s code block.