Skip to content
This repository was archived by the owner on Feb 13, 2025. It is now read-only.

Commit ade0412

Browse files
committed
asyncio: Optimize asyncio.sleep(0)
1 parent 5be2dac commit ade0412

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

Lib/asyncio/tasks.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -488,6 +488,10 @@ def _wait_for_one():
488488
@coroutine
489489
def sleep(delay, result=None, *, loop=None):
490490
"""Coroutine that completes after a given time (in seconds)."""
491+
if delay == 0:
492+
yield
493+
return result
494+
491495
future = futures.Future(loop=loop)
492496
h = future._loop.call_later(delay,
493497
future._set_result_unless_cancelled, result)

Lib/test/test_asyncio/test_tasks.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2188,5 +2188,29 @@ def test_run_coroutine_threadsafe_task_factory_exception(self):
21882188
self.assertEqual(context['exception'], exc_context.exception)
21892189

21902190

2191+
class SleepTests(test_utils.TestCase):
2192+
def setUp(self):
2193+
self.loop = asyncio.new_event_loop()
2194+
asyncio.set_event_loop(None)
2195+
2196+
def test_sleep_zero(self):
2197+
result = 0
2198+
2199+
def inc_result(num):
2200+
nonlocal result
2201+
result += num
2202+
2203+
@asyncio.coroutine
2204+
def coro():
2205+
self.loop.call_soon(inc_result, 1)
2206+
self.assertEqual(result, 0)
2207+
num = yield from asyncio.sleep(0, loop=self.loop, result=10)
2208+
self.assertEqual(result, 1) # inc'ed by call_soon
2209+
inc_result(num) # num should be 11
2210+
2211+
self.loop.run_until_complete(coro())
2212+
self.assertEqual(result, 11)
2213+
2214+
21912215
if __name__ == '__main__':
21922216
unittest.main()

0 commit comments

Comments
 (0)