8000 gh-130132: add an explicit close() call to urlopen examples without with by Mr-Sunglasses · Pull Request #130280 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

gh-130132: add an explicit close() call to urlopen examples without with #130280

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Mar 18, 2025
Merged
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions Doc/library/urllib.request.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1249,7 +1249,10 @@ It is also possible to achieve the same result without using the

>>> import urllib.request
>>> f = urllib.request.urlopen('http://www.python.org/')
>>> print(f.read(100).decode('utf-8'))
>>> try:
... print(f.read(100).decode('utf-8'))
... finally:
... f.close()
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtm

Expand Down Expand Up @@ -1294,7 +1297,10 @@ Use of Basic HTTP Authentication::
opener = urllib.request.build_opener(auth_handler)
# ...and install it globally so it can be used with urlopen.
urllib.request.install_opener(opener)
urllib.request.urlopen('http://www.example.com/login.html')
try:
r = urllib.request.urlopen('http://www.example.com/login.html')
finally:
r.close()

:func:`build_opener` provides many handlers by default, including a
:class:`ProxyHandler`. By default, :class:`ProxyHandler` uses the environment
Expand Down Expand Up @@ -1323,7 +1329,10 @@ Use the *headers* argument to the :class:`Request` constructor, or::
req.add_header('Referer', 'http://www.python.org/')
# Customize the default User-Agent header value:
req.add_header('User-Agent', 'urllib-example/0.1 (Contact: . . .)')
r = urllib.request.urlopen(req)
try:
r = urllib.request.urlopen(req)
finally:
r.close()

:class:`OpenerDirector` automatically adds a :mailheader:`User-Agent` header to
every :class:`Request`. To change this::
Expand Down
Loading
0