]> granicus.if.org Git - python/commitdiff
asyncio: allow None as wait timeout
authorVictor Stinner <victor.stinner@gmail.com>
Fri, 1 Apr 2016 19:39:09 +0000 (21:39 +0200)
committerVictor Stinner <victor.stinner@gmail.com>
Fri, 1 Apr 2016 19:39:09 +0000 (21:39 +0200)
Fix GH#325: Allow to pass None as a timeout value to disable timeout logic.

Change written by Andrew Svetlov and merged by Guido van Rossum.

Lib/asyncio/tasks.py
Lib/test/test_asyncio/test_tasks.py

index c37aa4195dba7c25f0dc52b7ab32308bb5029b52..cab4998ee44956152d8e5b6d58459f79b0a53d57 100644 (file)
@@ -401,7 +401,7 @@ def wait_for(fut, timeout, *, loop=None):
 
 @coroutine
 def _wait(fs, timeout, return_when, loop):
-    """Internal helper for wait() and _wait_for().
+    """Internal helper for wait() and wait_for().
 
     The fs argument must be a collection of Futures.
     """
@@ -747,7 +747,7 @@ def timeout(timeout, *, loop=None):
     ...     yield from coro()
 
 
-    timeout: timeout value in seconds
+    timeout: timeout value in seconds or None to disable timeout logic
     loop: asyncio compatible event loop
     """
     if loop is None:
@@ -768,8 +768,9 @@ class _Timeout:
         if self._task is None:
             raise RuntimeError('Timeout context manager should be used '
                                'inside a task')
-        self._cancel_handler = self._loop.call_later(
-            self._timeout, self._cancel_task)
+        if self._timeout is not None:
+            self._cancel_handler = self._loop.call_later(
+                self._timeout, self._cancel_task)
         return self
 
     def __exit__(self, exc_type, exc_val, exc_tb):
@@ -777,8 +778,9 @@ class _Timeout:
             self._cancel_handler = None
             self._task = None
             raise futures.TimeoutError
-        self._cancel_handler.cancel()
-        self._cancel_handler = None
+        if self._timeout is not None:
+            self._cancel_handler.cancel()
+            self._cancel_handler = None
         self._task = None
 
     def _cancel_task(self):
index acceb9b12aaeb13bd5a4557d1bd63398b3453c2e..40e5f8830fe0c05c604a13ca19d9d7d51ff74d65 100644 (file)
@@ -2382,6 +2382,22 @@ class TimeoutTests(test_utils.TestCase):
 
         self.loop.run_until_complete(go())
 
+    def test_timeout_disable(self):
+        @asyncio.coroutine
+        def long_running_task():
+            yield from asyncio.sleep(0.1, loop=self.loop)
+            return 'done'
+
+        @asyncio.coroutine
+        def go():
+            t0 = self.loop.time()
+            with asyncio.timeout(None, loop=self.loop):
+                resp = yield from long_running_task()
+            self.assertEqual(resp, 'done')
+            dt = self.loop.time() - t0
+            self.assertTrue(0.09 < dt < 0.11, dt)
+        self.loop.run_until_complete(go())
+
     def test_raise_runtimeerror_if_no_task(self):
         with self.assertRaises(RuntimeError):
             with asyncio.timeout(0.1, loop=self.loop):