Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 2ba8ece

Browse files
committed
asyncio: allow None as wait timeout
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.
1 parent ccdbe80 commit 2ba8ece

2 files changed

Lines changed: 24 additions & 6 deletions

File tree

Lib/asyncio/tasks.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -401,7 +401,7 @@ def wait_for(fut, timeout, *, loop=None):
401401

402402
@coroutine
403403
def _wait(fs, timeout, return_when, loop):
404-
"""Internal helper for wait() and _wait_for().
404+
"""Internal helper for wait() and wait_for().
405405
406406
The fs argument must be a collection of Futures.
407407
"""
@@ -747,7 +747,7 @@ def timeout(timeout, *, loop=None):
747747
... yield from coro()
748748
749749
750-
timeout: timeout value in seconds
750+
timeout: timeout value in seconds or None to disable timeout logic
751751
loop: asyncio compatible event loop
752752
"""
753753
if loop is None:
@@ -768,17 +768,19 @@ def __enter__(self):
768768
if self._task is None:
769769
raise RuntimeError('Timeout context manager should be used '
770770
'inside a task')
771-
self._cancel_handler = self._loop.call_later(
772-
self._timeout, self._cancel_task)
771+
if self._timeout is not None:
772+
self._cancel_handler = self._loop.call_later(
773+
self._timeout, self._cancel_task)
773774
return self
774775

775776
def __exit__(self, exc_type, exc_val, exc_tb):
776777
if exc_type is futures.CancelledError and self._cancelled:
777778
self._cancel_handler = None
778779
self._task = None
779780
raise futures.TimeoutError
780-
self._cancel_handler.cancel()
781-
self._cancel_handler = None
781+
if self._timeout is not None:
782+
self._cancel_handler.cancel()
783+
self._cancel_handler = None
782784
self._task = None
783785

784786
def _cancel_task(self):

Lib/test/test_asyncio/test_tasks.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2382,6 +2382,22 @@ def go():
23822382

23832383
self.loop.run_until_complete(go())
23842384

2385+
def test_timeout_disable(self):
2386+
@asyncio.coroutine
2387+
def long_running_task():
2388+
yield from asyncio.sleep(0.1, loop=self.loop)
2389+
return 'done'
2390+
2391+
@asyncio.coroutine
2392+
def go():
2393+
t0 = self.loop.time()
2394+
with asyncio.timeout(None, loop=self.loop):
2395+
resp = yield from long_running_task()
2396+
self.assertEqual(resp, 'done')
2397+
dt = self.loop.time() - t0
2398+
self.assertTrue(0.09 < dt < 0.11, dt)
2399+
self.loop.run_until_complete(go())
2400+
23852401
def test_raise_runtimeerror_if_no_task(self):
23862402
with self.assertRaises(RuntimeError):
23872403
with asyncio.timeout(0.1, loop=self.loop):

0 commit comments

Comments
 (0)