From 21c71bac5f684b0ec1665d841d05f91e078c3964 Mon Sep 17 00:00:00 2001 From: Senthil Kumaran Date: Tue, 13 Mar 2012 19:47:51 -0700 Subject: closes Issue12365 - Add an example explaining the context manager use case of urllib.urlopen --- Doc/library/urllib.request.rst | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/Doc/library/urllib.request.rst b/Doc/library/urllib.request.rst index cc759a4..b51ce3f 100644 --- a/Doc/library/urllib.request.rst +++ b/Doc/library/urllib.request.rst @@ -46,8 +46,8 @@ The :mod:`urllib.request` module defines the following functions: If neither *cafile* nor *capath* is specified, an HTTPS request will not do any verification of the server's certificate. - This function returns a file-like object with two additional methods from - the :mod:`urllib.response` module + This function returns a file-like object that works as a :term:`context manager`, + with two additional methods from the :mod:`urllib.response` module * :meth:`geturl` --- return the URL of the resource retrieved, commonly used to determine if a redirect was followed @@ -967,8 +967,17 @@ The following W3C document, http://www.w3.org/International/O-charset , lists the various ways in which a (X)HTML or a XML document could have specified its encoding information. -As python.org website uses *utf-8* encoding as specified in it's meta tag, we -will use same for decoding the bytes object. :: +As the python.org website uses *utf-8* encoding as specified in it's meta tag, we +will use the same for decoding the bytes object. :: + + >>> with urllib.request.urlopen('http://www.python.org/') as f: + ... print(f.read(100).decode('utf-8')) + ... + >> import urllib.request >>> f = urllib.request.urlopen('http://www.python.org/') @@ -976,7 +985,6 @@ will use same for decoding the bytes object. ::