[Python-checkins] cpython (3.4): asyncio: Optimize asyncio.sleep(0)

yury.selivanov python-checkins at python.org
Thu Nov 5 14:31:03 EST 2015


https://hg.python.org/cpython/rev/295459bd437f
changeset:   98974:295459bd437f
branch:      3.4
parent:      98955:030abe093847
user:        Yury Selivanov <yselivanov at sprymix.com>
date:        Thu Nov 05 14:29:04 2015 -0500
summary:
  asyncio: Optimize asyncio.sleep(0)

files:
  Lib/asyncio/tasks.py                |   4 ++
  Lib/test/test_asyncio/test_tasks.py |  24 +++++++++++++++++
  2 files changed, 28 insertions(+), 0 deletions(-)


diff --git a/Lib/asyncio/tasks.py b/Lib/asyncio/tasks.py
--- a/Lib/asyncio/tasks.py
+++ b/Lib/asyncio/tasks.py
@@ -488,6 +488,10 @@
 @coroutine
 def sleep(delay, result=None, *, loop=None):
     """Coroutine that completes after a given time (in seconds)."""
+    if delay == 0:
+        yield
+        return result
+
     future = futures.Future(loop=loop)
     h = future._loop.call_later(delay,
                                 future._set_result_unless_cancelled, result)
diff --git a/Lib/test/test_asyncio/test_tasks.py b/Lib/test/test_asyncio/test_tasks.py
--- a/Lib/test/test_asyncio/test_tasks.py
+++ b/Lib/test/test_asyncio/test_tasks.py
@@ -2188,5 +2188,29 @@
         self.assertEqual(context['exception'], exc_context.exception)
 
 
+class SleepTests(test_utils.TestCase):
+    def setUp(self):
+        self.loop = asyncio.new_event_loop()
+        asyncio.set_event_loop(None)
+
+    def test_sleep_zero(self):
+        result = 0
+
+        def inc_result(num):
+            nonlocal result
+            result += num
+
+        @asyncio.coroutine
+        def coro():
+            self.loop.call_soon(inc_result, 1)
+            self.assertEqual(result, 0)
+            num = yield from asyncio.sleep(0, loop=self.loop, result=10)
+            self.assertEqual(result, 1) # inc'ed by call_soon
+            inc_result(num) # num should be 11
+
+        self.loop.run_until_complete(coro())
+        self.assertEqual(result, 11)
+
+
 if __name__ == '__main__':
     unittest.main()

-- 
Repository URL: https://hg.python.org/cpython


More information about the Python-checkins mailing list