Skip to content

Commit c9fbdb0

Browse files
committed
fix: use context manager in urllib.request examples
1 parent 379b075 commit c9fbdb0

File tree

1 file changed

+5
-8
lines changed

1 file changed

+5
-8
lines changed

Doc/library/urllib.request.rst

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1297,10 +1297,8 @@ Use of Basic HTTP Authentication::
12971297
opener = urllib.request.build_opener(auth_handler)
12981298
# ...and install it globally so it can be used with urlopen.
12991299
urllib.request.install_opener(opener)
1300-
try:
1301-
r = urllib.request.urlopen('http://www.example.com/login.html')
1302-
finally:
1303-
r.close()
1300+
with urllib.request.urlopen('http://www.example.com/login.html') as r:
1301+
print(r.read().decode('utf-8'))
13041302

13051303
:func:`build_opener` provides many handlers by default, including a
13061304
:class:`ProxyHandler`. By default, :class:`ProxyHandler` uses the environment
@@ -1329,10 +1327,9 @@ Use the *headers* argument to the :class:`Request` constructor, or::
13291327
req.add_header('Referer', 'http://www.python.org/')
13301328
# Customize the default User-Agent header value:
13311329
req.add_header('User-Agent', 'urllib-example/0.1 (Contact: . . .)')
1332-
try:
1333-
r = urllib.request.urlopen(req)
1334-
finally:
1335-
r.close()
1330+
with urllib.request.urlopen(req) as r:
1331+
print(r.read().decode('utf-8'))
1332+
13361333

13371334
:class:`OpenerDirector` automatically adds a :mailheader:`User-Agent` header to
13381335
every :class:`Request`. To change this::

0 commit comments

Comments
 (0)