@@ -634,11 +634,17 @@ def ensure_future(coro_or_future, *, loop=None):
634
634
raise ValueError ('The future belongs to a different loop than '
635
635
'the one specified as the loop argument' )
636
636
return coro_or_future
637
- called_wrap_awaitable = False
637
+ should_close = False
638
638
if not coroutines .iscoroutine (coro_or_future ):
639
639
if inspect .isawaitable (coro_or_future ):
640
- coro_or_future = _wrap_awaitable (coro_or_future )
641
- called_wrap_awaitable = True
640
+ async def _wrap_awaitable ():
641
+ @types .coroutine
642
+ def wrapper ():
643
+ return (yield from coro_or_future .__await__ ())
644
+ return await wrapper ()
645
+
646
+ coro_or_future = _wrap_awaitable ()
647
+ should_close = True
642
648
else :
643
649
raise TypeError ('An asyncio.Future, a coroutine or an awaitable '
644
650
'is required' )
@@ -648,24 +654,11 @@ def ensure_future(coro_or_future, *, loop=None):
648
654
try :
649
655
return loop .create_task (coro_or_future )
650
656
except RuntimeError :
651
- if not called_wrap_awaitable :
657
+ if should_close :
652
658
coro_or_future .close ()
653
659
raise
654
660
655
661
656
- async def _wrap_awaitable (awaitable ):
657
- """Helper for asyncio.ensure_future().
658
-
659
- Wraps awaitable (an object with __await__) into a coroutine
660
- that will later be wrapped in a Task by ensure_future().
661
- """
662
-
663
- @types .coroutine
664
- def wrapper (awaitable ):
665
- return (yield from awaitable .__await__ ())
666
-
667
- return await wrapper (awaitable )
668
-
669
662
class _GatheringFuture (futures .Future ):
670
663
"""Helper for gather().
671
664
0 commit comments