Skip to content
This repository was archived by the owner on Nov 23, 2017. It is now read-only.

Commit

Permalink
Merge pull request #327 from python/zero_timeout
Browse files Browse the repository at this point in the history
Fix #325: Allow to pass None as a timeout value to disable timeout logic
  • Loading branch information
gvanrossum committed Mar 29, 2016
2 parents b6b6d28 + d3d4446 commit 13723e4
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
12 changes: 7 additions & 5 deletions asyncio/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -768,17 +768,19 @@ def __enter__(self):
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):
if exc_type is futures.CancelledError and self._cancelled:
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):
Expand Down
16 changes: 16 additions & 0 deletions tests/test_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -2382,6 +2382,22 @@ def go():

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):
Expand Down

0 comments on commit 13723e4

Please sign in to comment.