0% found this document useful (0 votes)
18 views1 page

15 Contextlib Closing Thing

The document discusses the contextlib module's closing class which closes the thing upon completion of a code block. It provides an example using closing to automatically close a URL page handle once falling out of a with statement's code block.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views1 page

15 Contextlib Closing Thing

The document discusses the contextlib module's closing class which closes the thing upon completion of a code block. It provides an example using closing to automatically close a URL page handle once falling out of a with statement's code block.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

contextlib.

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:

from contextlib import contextmanager

@contextmanager
def closing(db):
try:
yield db.conn()
finally:
db.close()

Basically what we’re doing is creating a closing function that’s wrapped in a


contextmanager. This is the equivalent of what the closing class does. The
difference is that instead of a decorator, we can use the closing class itself in
our with statement. Let’s take a look:

from contextlib import closing


from urllib.request import urlopen

with closing(urlopen('http://www.google.com')) as webpage:


for line in webpage:
# process the line
pass

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.

You might also like