changeset 68222:2f5f755b2687

Issue 9795: adds context manager protocol to nntplib.NNTP class so that it can used with the 'with' statement.
author Giampaolo Rodolà <g.rodola@gmail.com>
date Thu, 03 Mar 2011 18:34:06 +0000
parents 08804aea08f1
children d2b5bde5c1fa
files Doc/library/nntplib.rst Doc/whatsnew/3.3.rst Lib/nntplib.py Lib/test/test_nntplib.py
diffstat 4 files changed, 64 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/Doc/library/nntplib.rst	Thu Mar 03 18:21:02 2011 +0000
+++ b/Doc/library/nntplib.rst	Thu Mar 03 18:34:06 2011 +0000
@@ -70,10 +70,23 @@
    connecting to an NNTP server on the local machine and intend to call
    reader-specific commands, such as ``group``.  If you get unexpected
    :exc:`NNTPPermanentError`\ s, you might need to set *readermode*.
+   :class:`NNTP` class supports the :keyword:`with` statement to
+   unconditionally consume :exc:`socket.error` exceptions and to close the NNTP
+   connection when done. Here is a sample on how using it:
+
+    >>> from nntplib import NNTP
+    >>> with nntplib.NNTP('news.gmane.org') as n:
+    ...     n.group('gmane.comp.python.committers')
+    ...
+    ('211 1454 1 1454 gmane.comp.python.committers', '1454', '1', '1454', 'gmane.comp.python.committers')
+    >>>
+
 
    .. versionchanged:: 3.2
       *usenetrc* is now False by default.
 
+   .. versionchanged:: 3.3
+      Support for the :keyword:`with` statement was added.
 
 .. class:: NNTP_SSL(host, port=563, user=None, password=None, ssl_context=None, readermode=None, usenetrc=False, [timeout])
 
--- a/Doc/whatsnew/3.3.rst	Thu Mar 03 18:21:02 2011 +0000
+++ b/Doc/whatsnew/3.3.rst	Thu Mar 03 18:34:06 2011 +0000
@@ -88,6 +88,22 @@
 
   (Patch submitted by Giampaolo RodolĂ  in :issue:`10784`.)
 
+nntplib
+-------
+
+The :class:`nntplib.NNTP` class now supports the context manager protocol to
+unconditionally consume :exc:`socket.error` exceptions and to close the NNTP
+connection when done::
+
+  >>> from nntplib import NNTP
+  >>> with nntplib.NNTP('news.gmane.org') as n:
+  ...     n.group('gmane.comp.python.committers')
+  ...
+  ('211 1454 1 1454 gmane.comp.python.committers', '1454', '1', '1454', 'gmane.comp.python.committers')
+  >>>
+
+(Contributed by Giampaolo RodolĂ  in :issue:`9795`)
+
 Optimizations
 =============
 
--- a/Lib/nntplib.py	Thu Mar 03 18:21:02 2011 +0000
+++ b/Lib/nntplib.py	Thu Mar 03 18:34:06 2011 +0000
@@ -346,6 +346,20 @@
         # Log in and encryption setup order is left to subclasses.
         self.authenticated = False
 
+    def __enter__(self):
+        return self
+
+    def __exit__(self, *args):
+        is_connected = lambda: hasattr(self, "file")
+        if is_connected():
+            try:
+                self.quit()
+            except (socket.error, EOFError):
+                pass
+            finally:
+                if is_connected():
+                    self._close()
+
     def getwelcome(self):
         """Get the welcome message from the server
         (this is read and squirreled away by __init__()).
--- a/Lib/test/test_nntplib.py	Thu Mar 03 18:21:02 2011 +0000
+++ b/Lib/test/test_nntplib.py	Thu Mar 03 18:34:06 2011 +0000
@@ -1,4 +1,5 @@
 import io
+import socket
 import datetime
 import textwrap
 import unittest
@@ -252,6 +253,26 @@
             # value
             setattr(cls, name, wrap_meth(meth))
 
+    def test_with_statement(self):
+        def is_connected():
+            if not hasattr(server, 'file'):
+                return False
+            try:
+                server.help()
+            except (socket.error, EOFError):
+                return False
+            return True
+
+        with self.NNTP_CLASS(self.NNTP_HOST, timeout=TIMEOUT, usenetrc=False) as server:
+            self.assertTrue(is_connected())
+            self.assertTrue(server.help())
+        self.assertFalse(is_connected())
+
+        with self.NNTP_CLASS(self.NNTP_HOST, timeout=TIMEOUT, usenetrc=False) as server:
+            server.quit()
+        self.assertFalse(is_connected())
+
+
 NetworkedNNTPTestsMixin.wrap_methods()