]> granicus.if.org Git - python/commitdiff
asyncio: Optimize asyncio.sleep(0)
authorYury Selivanov <yselivanov@sprymix.com>
Thu, 5 Nov 2015 19:29:04 +0000 (14:29 -0500)
committerYury Selivanov <yselivanov@sprymix.com>
Thu, 5 Nov 2015 19:29:04 +0000 (14:29 -0500)
Lib/asyncio/tasks.py
Lib/test/test_asyncio/test_tasks.py

index b887d88934f27f622f12f8a3ae3731c727541f1e..77a93e0fe0aee6d8987f887e0cfd1b880a8e107d 100644 (file)
@@ -488,6 +488,10 @@ def as_completed(fs, *, loop=None, timeout=None):
 @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)
index 9772baed1c5a2e0562ba93ceaf7d7676831994b6..b492cf0153c591f36284fd1c7e7ef77448889164 100644 (file)
@@ -2188,5 +2188,29 @@ class RunCoroutineThreadsafeTests(test_utils.TestCase):
         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()