{"id":333,"date":"2024-01-28T11:01:48","date_gmt":"2024-01-28T11:01:48","guid":{"rendered":"https:\/\/learnpython.elegantwallp.com\/?p=333"},"modified":"2024-01-28T11:01:49","modified_gmt":"2024-01-28T11:01:49","slug":"python-asyncio-future","status":"publish","type":"post","link":"https:\/\/learnpython.elegantwallp.com\/2024\/01\/28\/python-asyncio-future\/","title":{"rendered":"Python asyncio Future"},"content":{"rendered":"\n<p><strong>Summary<\/strong>: in this tutorial, you\u2019ll learn about Python&nbsp;<code>asyncio<\/code>&nbsp;future objects and understand how they work.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Introduction to the Python asyncio future<\/h2>\n\n\n\n<p>A future is an object that returns a value later in the future but not now. Typically, a future object is the result of an asynchronous operation.<\/p>\n\n\n\n<p>For example, you may call an API from a remote server and expect to receive the result later. The API call may return a future object so that you can await it.<\/p>\n\n\n\n<p>To create a future object, you use the\u00a0<code>Future<\/code>\u00a0class from the\u00a0<code>asyncio<\/code>\u00a0package. Consider the following example:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>import asyncio from asyncio import Future async def main(): my_future = Future() print(my_future.done()) <em># False<\/em> my_future.set_result('Bright') print(my_future.done()) <em># True<\/em> print(my_future.result()) asyncio.run(main())<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>How it works.<\/p>\n\n\n\n<p>First, import\u00a0<code>Future<\/code>\u00a0class from the\u00a0<code>asyncio<\/code>\u00a0library:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>from asyncio import Future<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Next, create a new\u00a0<code>Future<\/code>\u00a0object in the\u00a0<code>main()<\/code>\u00a0coroutine:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>my_future = Future()<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>A newly created future doesn\u2019t have any value because it doesn\u2019t exist yet. In this state, the future is considered incomplete, unresolved, or not done.<\/p>\n\n\n\n<p>Then, call the\u00a0<code>done()<\/code>\u00a0method to check the status of the future object:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>print(my_future.done()) <em># False<\/em><\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>It returns&nbsp;<code>False<\/code>.<\/p>\n\n\n\n<p>After that, set a value for the future object by calling the\u00a0<code>set_result()<\/code>\u00a0method:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>my_future.set_result('Bright')<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Once you set the value, the future is done. Calling the\u00a0<code>done()<\/code>\u00a0method of the future object in this stage returns\u00a0<code>True<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>print(my_future.done()) <em># True<\/em><\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Finally, get the result from the future object by calling its\u00a0<code>result()<\/code>\u00a0method:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>print(my_future.result())<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">Using Python asyncio future with await<\/h2>\n\n\n\n<p>When you use the\u00a0<code>await<\/code>\u00a0keyword with a future, you pause the future until it returns a value. The following example shows how to use the future with\u00a0<code>await<\/code>\u00a0keyword:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>from asyncio import Future import asyncio async def plan(my_future): print('Planning my future...') await asyncio.sleep(1) my_future.set_result('Bright') def create() -> Future: my_future = Future() asyncio.create_task(plan(my_future)) return my_future async def main(): my_future = create() result = await my_future print(result) asyncio.run(main())<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Output:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>Planning my future... Bright<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>How it works.<\/p>\n\n\n\n<p>First, define a coroutine that accepts a future and sets its value after 1 second:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>async def plan(my_future: Future): print('Planning my future...') await asyncio.sleep(1) my_future.set_result('Bright')<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Second, define a\u00a0<code>create()<\/code>\u00a0function that schedules the\u00a0<code>plan()<\/code>\u00a0coroutine as a task and returns a future object:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>def create() -> Future: my_future = Future() asyncio.create_task(plan(my_future)) return my_future<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>Third, call the\u00a0<code>create()<\/code>\u00a0function that returns a future, use the await keyword to wait for the future to return a result, and display it:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>async def main(): my_future = create() result = await my_future print(result)<\/code><small>Code language: Python (python)<\/small><\/code><\/pre>\n\n\n\n<p>In practice, you\u2019ll rarely need to create&nbsp;<code>Future<\/code>&nbsp;objects directly. However, you\u2019ll use the&nbsp;<code>Future<\/code>&nbsp;objects returned from API. Therefore, it\u2019s important to understand how the&nbsp;<code>Future<\/code>&nbsp;works.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Futures, Tasks, and Coroutines<\/h2>\n\n\n\n<p>The following class hierarchy shows the relationships between\u00a0Coroutine, Future, and\u00a0Task:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/www.pythontutorial.net\/wp-content\/uploads\/2022\/07\/python-future.svg\" alt=\"\" class=\"wp-image-4160\"\/><\/figure>\n\n\n\n<p>In this class hierarchy, Courtine, Future, and Task are subclasses of the Awaitable abstract class.<\/p>\n\n\n\n<p>The&nbsp;<code>Awaitable<\/code>&nbsp;class has an abstract method&nbsp;<code>__await__()<\/code>. Any class that has the implementation of the&nbsp;<code>__await__()<\/code>&nbsp;method can be used with the await keyword. And the objects of classes that can be used with the&nbsp;<code>await<\/code>&nbsp;keyword are called&nbsp;<em>awaitables<\/em>.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Summary: in this tutorial, you\u2019ll learn about Python&nbsp;asyncio&nbsp;future objects and understand how they work. Introduction to the Python asyncio future A future is an object that returns a value later in the future but not now. Typically, a future object is the result of an asynchronous operation. For example, you may call an API from [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[41],"tags":[],"class_list":["post-333","post","type-post","status-publish","format-standard","hentry","category-1-python-concurrency"],"_links":{"self":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/333","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/comments?post=333"}],"version-history":[{"count":1,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/333\/revisions"}],"predecessor-version":[{"id":334,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/posts\/333\/revisions\/334"}],"wp:attachment":[{"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/media?parent=333"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/categories?post=333"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/learnpython.elegantwallp.com\/wp-json\/wp\/v2\/tags?post=333"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}