[Python-checkins] cpython (merge 3.2 -> default): default: closes Issue12365 - Add an example explaining the context manager use

senthil.kumaran python-checkins at python.org
Wed Mar 14 03:48:49 CET 2012


http://hg.python.org/cpython/rev/074e12441ed6
changeset:   75619:074e12441ed6
parent:      75617:53715804dc71
parent:      75618:8625627969aa
user:        Senthil Kumaran <senthil at uthcode.com>
date:        Tue Mar 13 19:48:37 2012 -0700
summary:
  default: closes Issue12365 - Add an example explaining the context manager use case of urllib.urlopen

files:
  Doc/library/urllib.request.rst |  18 +++++++++++++-----
  1 files changed, 13 insertions(+), 5 deletions(-)


diff --git a/Doc/library/urllib.request.rst b/Doc/library/urllib.request.rst
--- a/Doc/library/urllib.request.rst
+++ b/Doc/library/urllib.request.rst
@@ -46,8 +46,8 @@
       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
@@ -998,8 +998,17 @@
 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'))
+   ...
+   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+   "http://www.w3.org/TR/xhtml1/DTD/xhtm
+
+It is also possible to achieve the same result without using the
+:term:`context manager` approach. ::
 
    >>> import urllib.request
    >>> f = urllib.request.urlopen('http://www.python.org/')
@@ -1007,7 +1016,6 @@
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtm
 
-
 In the following example, we are sending a data-stream to the stdin of a CGI
 and reading the data it returns to us. Note that this example will only work
 when the Python installation supports SSL. ::

-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list