From 424298a155b5cc652ce1e539a1fedb658fba9cd1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Giampaolo=20Rodol=C3=A0?= Date: Thu, 3 Mar 2011 18:34:06 +0000 Subject: Issue 9795: adds context manager protocol to nntplib.NNTP class so that it can used with the 'with' statement. --- Lib/nntplib.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) (limited to 'Lib/nntplib.py') diff --git a/Lib/nntplib.py b/Lib/nntplib.py index 70a75b60d2..ba701920d1 100644 --- a/Lib/nntplib.py +++ b/Lib/nntplib.py @@ -346,6 +346,20 @@ class _NNTPBase: # 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__()). -- cgit v1.2.1