{"id":732,"date":"2022-02-01T14:44:00","date_gmt":"2022-02-01T09:14:00","guid":{"rendered":"https:\/\/geekpython.in\/?p=732"},"modified":"2023-08-15T17:20:48","modified_gmt":"2023-08-15T11:50:48","slug":"asyncio-how-to-use-asyncawait-in-python","status":"publish","type":"post","link":"https:\/\/geekpython.in\/asyncio-how-to-use-asyncawait-in-python","title":{"rendered":"asyncio &#8211; How to use Async\/Await in Python."},"content":{"rendered":"\n<p>In this article, we will discuss&nbsp;<strong>how we can use async\/await in Python.<\/strong><\/p>\n\n\n\n<p>If you&#8217;re familiar with JavaScript, you&#8217;ll notice that we use&nbsp;<code>async<\/code>, which causes a function to return a promise, and&nbsp;<code>await<\/code>, which causes a function to wait for a promise.<\/p>\n\n\n\n<p>When we need to fetch some data from the servers, we use&nbsp;<code>async<\/code>&nbsp;and&nbsp;<code>await<\/code>&nbsp;to delay the function&#8217;s execution until the promise is resolved, and in the meantime, the other functions are executed without blocking the other tasks.<\/p>\n\n\n\n<p>This happens because the code is executed&nbsp;<strong>asynchronously<\/strong>.<\/p>\n\n\n\n<p>Well, this is not the JavaScript tutorial so we don&#8217;t dive deep into the working of&nbsp;<code>asynchronous<\/code>&nbsp;operations in JavaScript.<\/p>\n\n\n\n<p>But we&#8217;ll learn the meaning of&nbsp;<strong>Asynchronous<\/strong>&nbsp;ahead in this article.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"heading-introduction\"><a href=\"https:\/\/geekpython.in\/asyncio-how-to-use-asyncawait-in-python#heading-introduction\"><\/a>Introduction<\/h1>\n\n\n\n<p>Just above we encountered the term&nbsp;<strong>Asynchronous<\/strong>. What does it mean?<\/p>\n\n\n\n<p>For simple understanding, it just means that&nbsp;<strong>not occurring at the same time<\/strong>. It is theoretical meaning. We gonna learn the Practical definition of&nbsp;<strong>asynchronous<\/strong>&nbsp;ahead of this article with an example that lets you understand it easily.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1920\" height=\"1102\" src=\"https:\/\/geekpython.in\/wp-content\/uploads\/2023\/08\/async-await.png\" alt=\"Visual Representation of Synchronous and Asynchronous\" class=\"wp-image-734\"\/><\/figure>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"heading-asyncio-asynchronous-io\"><a href=\"https:\/\/geekpython.in\/asyncio-how-to-use-asyncawait-in-python#heading-asyncio-asynchronous-io\"><\/a>asyncio\u00a0&#8211; Asynchronous IO <\/h1>\n\n\n\n<p>We cannot use&nbsp;<code>async<\/code>\/<code>await<\/code>&nbsp;syntax directly in the function to make it asynchronous rather we can use a Python package&nbsp;<code>asyncio<\/code>&nbsp;to achieve the goal.<\/p>\n\n\n\n<p>Before diving into the&nbsp;<strong>asyncio<\/strong>&nbsp;module let&#8217;s understand&nbsp;<strong>Asynchronous IO<\/strong>&nbsp;first.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p><strong>Note: I refer to asynchronous IO as async IO and<\/strong>&nbsp;<code>asyncio<\/code>&nbsp;is a Python package.<\/p>\n<\/blockquote>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"heading-asynchronous-io\"><a href=\"https:\/\/geekpython.in\/asyncio-how-to-use-asyncawait-in-python#heading-asynchronous-io\"><\/a>Asynchronous IO <\/h1>\n\n\n\n<p>async IO is designed to work on concurrent programming that has received support in Python, from Python 3.4 through Python 3.7 and beyond this.<\/p>\n\n\n\n<p>Let&#8217;s understand it with the help of an example:<\/p>\n\n\n\n<p><strong>We will understand it by the example of a chess master Judit Polg\u00e1r.<\/strong><\/p>\n\n\n\n<p>Judit Polg\u00e1r, a chess master hosts a chess exhibition in which some amateur players took part and she plays with them. She has two ways of conducting the exhibition:&nbsp;<strong>synchronously<\/strong>&nbsp;and&nbsp;<strong>asynchronously<\/strong>.<\/p>\n\n\n\n<p>Here are the assumptions:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>There are 24 opponents.<\/li>\n\n\n\n<li>Judit makes each chess move in 5 seconds.<\/li>\n\n\n\n<li>Opponents each take 55 seconds to make a move.<\/li>\n\n\n\n<li>Games average 30 pair moves (60 moves total).<\/li>\n<\/ul>\n\n\n\n<p><strong>Synchronous approach:<\/strong><\/p>\n\n\n\n<p>Judit only plays one game at a time and never moves on until the current game is finished. Each game lasts&nbsp;<strong>(55 + 5) 30 = 1800 seconds<\/strong>&nbsp;or&nbsp;<strong>30 minutes<\/strong>. The duration of the exhibition is&nbsp;<strong>24*30 = 720 minutes<\/strong>&nbsp;or&nbsp;<strong>12 hours<\/strong>.<\/p>\n\n\n\n<p><strong>Asynchronous approach:<\/strong><\/p>\n\n\n\n<p>Judit moves from table to table in this method, making one move at each table. She leaves the table after each move and waits for the opponent to make their next move.<\/p>\n\n\n\n<p>Judit Polg\u00e1r takes&nbsp;<strong>24*5 = 120<\/strong>&nbsp;<strong><em>seconds<\/em><\/strong>&nbsp;or&nbsp;<strong>2 minutes<\/strong>&nbsp;to complete one move on all 24 games. As a result, the entire exhibition has been reduced to&nbsp;<strong>120*30 = 3600<\/strong>&nbsp;<strong>seconds<\/strong>&nbsp;or just&nbsp;<strong>1 hour<\/strong>.<\/p>\n\n\n\n<p><strong>From the above example, it concludes that async IO tasks that take a long waiting period get blocked and allow other tasks to run during that downtime.<\/strong><\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>The&nbsp;<a target=\"_blank\" href=\"https:\/\/www.youtube.com\/watch?v=iG6fr81xHKA&amp;t=254s\" rel=\"noreferrer noopener\">Source<\/a>&nbsp;of this example.<\/p>\n<\/blockquote>\n\n\n\n<p>Let&#8217;s move to the next part of this article.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"heading-pythons-asyncio-module\"><a href=\"https:\/\/geekpython.in\/asyncio-how-to-use-asyncawait-in-python#heading-pythons-asyncio-module\"><\/a>Python&#8217;s\u00a0asyncio\u00a0module <\/h1>\n\n\n\n<p>According to documentation,&nbsp;<code>asyncio<\/code>&nbsp;is a type of library that helps us to write concurrent code using&nbsp;<code>async<\/code>\/<code>await<\/code>&nbsp;syntax.<\/p>\n\n\n\n<p>Since it&#8217;s a module we have to import it.<\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">import asyncio<\/pre><\/div>\n\n\n\n<p><code>asyncio<\/code>&nbsp;works with&nbsp;<strong>Coroutines<\/strong>. Coroutines are nothing but a specialized version of Python generator functions.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>A coroutine is a function that can suspend its execution before reaching the return and it can indirectly pass the control to another coroutine for some time.<\/p>\n\n\n\n<p>Coroutines declared with the&nbsp;<strong>async\/await<\/strong>&nbsp;syntax is the preferred way of writing&nbsp;<strong>asyncio<\/strong>&nbsp;applications.<\/p>\n<\/blockquote>\n\n\n\n<p><strong>Here&#8217;s the simple use case:<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \">import asyncio\n\nasync def func():\n    print(\"Hey....\")\n    await asyncio.sleep(1)\n    print(\"I am here...\")\n\nasyncio.run(func())<\/pre><\/div>\n\n\n\n<ol class=\"wp-block-list\">\n<li><code>async def func()<\/code>&nbsp;&#8211; We used&nbsp;<code>async<\/code>&nbsp;to make the function asynchronous.<\/li>\n\n\n\n<li><code>await asyncio.sleep(1)<\/code>&nbsp;&#8211; Here, we used&nbsp;<code>await<\/code>&nbsp;and used the&nbsp;<code>asyncio.sleep()<\/code>&nbsp;to delay the execution of the&nbsp;<code>print<\/code>&nbsp;statement below it.<\/li>\n\n\n\n<li><code>asyncio.run(func())<\/code>&nbsp;&#8211; Finally, we are calling the function. You can see that we used&nbsp;<code>asyncio<\/code>&nbsp;to call the function, if we try to call the function simply as usual then we get a&nbsp;<code>RuntimeError<\/code>.<\/li>\n<\/ol>\n\n\n\n<p><strong>Note: You must be on Python 3.7 or above.<\/strong><\/p>\n\n\n\n<p>Until here, you surely get some idea of&nbsp;<strong>Asynchronous IO<\/strong>&nbsp;and&nbsp;<strong>asyncio<\/strong>&nbsp;use cases.<\/p>\n\n\n\n<p>Let&#8217;s look at the examples demonstrating the&nbsp;<strong>Asynchronous<\/strong>&nbsp;function:<\/p>\n\n\n\n<p><strong>Asynchronous<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" title=\"asynchronous.py\">import asyncio\n\nasync def write():\n    print(\"Hey\")\n    await asyncio.sleep(1)\n    print(\"there\")\n\nasync def main():\n    await asyncio.gather(write(), write(), write())\n\nif __name__ == \"__main__\":\n    import time\n    start = time.perf_counter()\n    asyncio.run(main())\n    elapsed = time.perf_counter() - start\n    print(f\"File executed in {elapsed:0.2f} seconds\")<\/pre><\/div>\n\n\n\n<ol class=\"wp-block-list\">\n<li>We created two&nbsp;<code>async<\/code>&nbsp;functions &#8211;<\/li>\n\n\n\n<li>First is the&nbsp;<code>write()<\/code>&nbsp;function that prints&nbsp;<code>Hey<\/code>&nbsp;then wait for 1 second and then again prints&nbsp;<code>there<\/code>.<\/li>\n\n\n\n<li>Second is&nbsp;<code>main()<\/code>&nbsp;function that executes<code>write()<\/code>&nbsp;function 3 times using&nbsp;<code>asyncio.gather()<\/code>.<\/li>\n\n\n\n<li>And then we wrote a code that calculates the time taken to execute the&nbsp;<code>async<\/code>&nbsp;functions.<\/li>\n<\/ol>\n\n\n\n<p><strong><em>Here&#8217;s the output:<\/em><\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1920\" height=\"648\" src=\"https:\/\/geekpython.in\/wp-content\/uploads\/2023\/08\/outputasynch.png\" alt=\"Asynchrounous Output\" class=\"wp-image-738\"\/><\/figure>\n\n\n\n<p><strong>We can clearly see that the whole code was executed in just 1 second using the asynchronous approach.<\/strong><\/p>\n\n\n\n<p>What if we execute the same code in a&nbsp;<strong>Synchronous<\/strong>&nbsp;way:<\/p>\n\n\n\n<p><strong>Synchronous<\/strong><\/p>\n\n\n\n<div class=\"wp-block-urvanov-syntax-highlighter-code-block\"><pre class=\"lang:python decode:true \" title=\"synchronous.py\">import time\n\ndef write():\n    print(\"Hey\")\n    time.sleep(1)\n    print(\"there\")\n\ndef main():\n    for _ in range(3):\n        write()\n\nif __name__ == \"__main__\":\n    start = time.perf_counter()\n    main()\n    elapsed = time.perf_counter() - start\n    print(f\"File executed in {elapsed:0.2f} seconds\")<\/pre><\/div>\n\n\n\n<p><strong><em>Here&#8217;s the output:<\/em><\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"1920\" height=\"648\" src=\"https:\/\/geekpython.in\/wp-content\/uploads\/2023\/08\/outputasync-1.png\" alt=\"Synchronous Output\" class=\"wp-image-736\"\/><\/figure>\n\n\n\n<p><strong>Here, this code snippet took 3 seconds to execute using the synchronous approach.<\/strong><\/p>\n\n\n\n<p>Now we are clearly able to see the differences in both approaches and even understand how it&#8217;s happened.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\" id=\"heading-conclusion\"><a href=\"https:\/\/geekpython.in\/asyncio-how-to-use-asyncawait-in-python#heading-conclusion\"><\/a>Conclusion<\/h1>\n\n\n\n<p>We can use&nbsp;<code>async<\/code>\/<code>await<\/code>&nbsp;in Python to make the high-level structured code network for better efficiency.<\/p>\n\n\n\n<p><code>asyncio<\/code>&nbsp;is used as a foundation for various Python asynchronous frameworks that provide high-performance networks and web servers, database connection libraries, distributed task queues, etc.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>\ud83c\udfc6<strong>Other articles you might be interested in if you liked this one<\/strong><\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/match-case-in-python\" rel=\"noreferrer noopener\">Performing pattern matching using match-case statements in Python<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/super-in-python\" rel=\"noreferrer noopener\">How to use super() function in Python classes<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/class-inheritance-in-python\" rel=\"noreferrer noopener\">Different types of inheritances in Python classes<\/a>.<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/implement-getitem-setitem-and-delitem-in-python\" rel=\"noreferrer noopener\">How to implement __getitem__, __setitem__ and __delitem__ in Python classes<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/str-and-repr-in-python\" rel=\"noreferrer noopener\">How to change the string representation of the objects in Python<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/python-sort-vs-sorted\" rel=\"noreferrer noopener\">What is the difference between sort() and sorted() function in Python<\/a>?<\/p>\n\n\n\n<p>\u2705<a target=\"_blank\" href=\"https:\/\/geekpython.in\/access-modifiers-in-python\" rel=\"noreferrer noopener\">Public, Protected, and Private access modifiers in Python<\/a>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><strong>That&#8217;s all for now<\/strong><\/p>\n\n\n\n<p><strong>Keep coding\u270c\u270c<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In this article, we will discuss&nbsp;how we can use async\/await in Python. If you&#8217;re familiar with JavaScript, you&#8217;ll notice that we use&nbsp;async, which causes a function to return a promise, and&nbsp;await, which causes a function to wait for a promise. When we need to fetch some data from the servers, we use&nbsp;async&nbsp;and&nbsp;await&nbsp;to delay the function&#8217;s [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":739,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"ocean_post_layout":"","ocean_both_sidebars_style":"","ocean_both_sidebars_content_width":0,"ocean_both_sidebars_sidebars_width":0,"ocean_sidebar":"0","ocean_second_sidebar":"0","ocean_disable_margins":"enable","ocean_add_body_class":"","ocean_shortcode_before_top_bar":"","ocean_shortcode_after_top_bar":"","ocean_shortcode_before_header":"","ocean_shortcode_after_header":"","ocean_has_shortcode":"","ocean_shortcode_after_title":"","ocean_shortcode_before_footer_widgets":"","ocean_shortcode_after_footer_widgets":"","ocean_shortcode_before_footer_bottom":"","ocean_shortcode_after_footer_bottom":"","ocean_display_top_bar":"default","ocean_display_header":"default","ocean_header_style":"","ocean_center_header_left_menu":"0","ocean_custom_header_template":"0","ocean_custom_logo":0,"ocean_custom_retina_logo":0,"ocean_custom_logo_max_width":0,"ocean_custom_logo_tablet_max_width":0,"ocean_custom_logo_mobile_max_width":0,"ocean_custom_logo_max_height":0,"ocean_custom_logo_tablet_max_height":0,"ocean_custom_logo_mobile_max_height":0,"ocean_header_custom_menu":"0","ocean_menu_typo_font_family":"0","ocean_menu_typo_font_subset":"","ocean_menu_typo_font_size":0,"ocean_menu_typo_font_size_tablet":0,"ocean_menu_typo_font_size_mobile":0,"ocean_menu_typo_font_size_unit":"px","ocean_menu_typo_font_weight":"","ocean_menu_typo_font_weight_tablet":"","ocean_menu_typo_font_weight_mobile":"","ocean_menu_typo_transform":"","ocean_menu_typo_transform_tablet":"","ocean_menu_typo_transform_mobile":"","ocean_menu_typo_line_height":0,"ocean_menu_typo_line_height_tablet":0,"ocean_menu_typo_line_height_mobile":0,"ocean_menu_typo_line_height_unit":"","ocean_menu_typo_spacing":0,"ocean_menu_typo_spacing_tablet":0,"ocean_menu_typo_spacing_mobile":0,"ocean_menu_typo_spacing_unit":"","ocean_menu_link_color":"","ocean_menu_link_color_hover":"","ocean_menu_link_color_active":"","ocean_menu_link_background":"","ocean_menu_link_hover_background":"","ocean_menu_link_active_background":"","ocean_menu_social_links_bg":"","ocean_menu_social_hover_links_bg":"","ocean_menu_social_links_color":"","ocean_menu_social_hover_links_color":"","ocean_disable_title":"default","ocean_disable_heading":"default","ocean_post_title":"","ocean_post_subheading":"","ocean_post_title_style":"","ocean_post_title_background_color":"","ocean_post_title_background":0,"ocean_post_title_bg_image_position":"","ocean_post_title_bg_image_attachment":"","ocean_post_title_bg_image_repeat":"","ocean_post_title_bg_image_size":"","ocean_post_title_height":0,"ocean_post_title_bg_overlay":0.5,"ocean_post_title_bg_overlay_color":"","ocean_disable_breadcrumbs":"default","ocean_breadcrumbs_color":"","ocean_breadcrumbs_separator_color":"","ocean_breadcrumbs_links_color":"","ocean_breadcrumbs_links_hover_color":"","ocean_display_footer_widgets":"default","ocean_display_footer_bottom":"default","ocean_custom_footer_template":"0","ocean_post_oembed":"","ocean_post_self_hosted_media":"","ocean_post_video_embed":"","ocean_link_format":"","ocean_link_format_target":"self","ocean_quote_format":"","ocean_quote_format_link":"post","ocean_gallery_link_images":"off","ocean_gallery_id":[],"footnotes":""},"categories":[2],"tags":[12],"class_list":["post-732","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-python","tag-python","entry","has-media"],"_links":{"self":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/732","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/comments?post=732"}],"version-history":[{"count":3,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/732\/revisions"}],"predecessor-version":[{"id":1385,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/posts\/732\/revisions\/1385"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media\/739"}],"wp:attachment":[{"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/media?parent=732"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/categories?post=732"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/geekpython.in\/wp-json\/wp\/v2\/tags?post=732"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}