Python asyncio: return vs set_result -
hello asyncio experts,
how correctly return results coroutine? need use return or future.set_result?
for example:
@coroutine def do_something() result = yield some_function() return result or
@coroutine def do_something() future = asyncio.future() result = yield some_function() future.set_result(result)
you should use return result. second example end returning none, rather result. here's complete example demonstrating that:
from asyncio import coroutine import asyncio @asyncio.coroutine def some_function(): yield asyncio.sleep(.5) return 5 @coroutine def do_something(): result = yield some_function() return result @coroutine def do_something_else(): future = asyncio.future() result = yield some_function() future.set_result(result) @coroutine def main(): print((yield do_something())) print((yield do_something_else())) loop = asyncio.get_event_loop() loop.run_until_complete(main()) output:
5 none note become equivalent caller's perspective if return future do_something_else:
@coroutine def do_something_else(): future = asyncio.future() result = yield some_function() future.set_result(result) return future # yield do_something_else() returns 5. but it's unnecessary work when can return result directly.
in vast majority of cases, coroutines don't need explicitly create future , call set_result on @ all. pattern useful, see in unit tests , frameworks, rather in application code.
one interesting use of implementation of asyncio.sleep:
@coroutine def sleep(delay, result=none, *, loop=none): """coroutine completes after given time (in seconds).""" future = futures.future(loop=loop) h = future._loop.call_later(delay, future.set_result, result) try: return (yield future) finally: h.cancel() here future created, set_result method future scheduled called after long caller wants sleep, , yield from called on future, make function wait long delay was, @ point future.set_result(result) called, , yield from call completes.
Comments
Post a Comment