|
| 1 | +--- |
| 2 | +Title: 'async' |
| 3 | +Description: 'Allows users to define an asynchronous function in Python.' |
| 4 | +Subjects: |
| 5 | + - 'Computer Science' |
| 6 | + - 'Data Science' |
| 7 | +Tags: |
| 8 | + - 'Async Await' |
| 9 | + - 'Functions' |
| 10 | + - 'Python' |
| 11 | +CatalogContent: |
| 12 | + - 'learn-python-3' |
| 13 | + - 'paths/computer-science' |
| 14 | +--- |
| 15 | + |
| 16 | +The **`async`** keyword defines an [asynchronous function](https://www.codecademy.com/article/wix-what-is-async-and-await) in Python. Asynchronous functions let a program handle multiple tasks concurrently without waiting for each to finish, improving efficiency and enabling non-blocking execution. |
| 17 | + |
| 18 | +## Syntax |
| 19 | + |
| 20 | +```pseudo |
| 21 | +import asyncio |
| 22 | +
|
| 23 | +async def function_name(parameters): |
| 24 | + # Function body |
| 25 | + await #awaitable code |
| 26 | +``` |
| 27 | + |
| 28 | +In the syntax: |
| 29 | + |
| 30 | +- `import asyncio`: Imports Python’s built-in library for running and managing asynchronous tasks. |
| 31 | +- `async`: The `async` keyword is declared before [`def`](https://www.codecademy.com/resources/docs/python/keywords/def) to define an asynchronous function (coroutine). |
| 32 | +- `await`: Used inside an async function to pause execution until the awaited coroutine or awaitable object completes. |
| 33 | + |
| 34 | +**Parameters:** |
| 35 | + |
| 36 | +Same as a regular function, any number of positional or keyword arguments. |
| 37 | + |
| 38 | +**Return value:** |
| 39 | + |
| 40 | +Returns a coroutine object, which must be awaited (using `await`) to get the actual result. |
| 41 | + |
| 42 | +> **Note:** If an `async` function doesn’t contain any `await` statements, it will still be valid but won’t perform any asynchronous operations. |
| 43 | +
|
| 44 | +## Example 1 |
| 45 | + |
| 46 | +In this example, the async function `hello()` prints the first half of 'Hello world!', waits 3 seconds, and then prints the second half: |
| 47 | + |
| 48 | +```py |
| 49 | +import asyncio |
| 50 | + |
| 51 | +async def hello(): |
| 52 | + print("Hello") |
| 53 | + await asyncio.sleep(3) # Pauses for 3 seconds |
| 54 | + print("world!") |
| 55 | +``` |
| 56 | + |
| 57 | +Here is the output of this code: |
| 58 | + |
| 59 | +```shell |
| 60 | +Hello |
| 61 | +world! |
| 62 | +``` |
| 63 | + |
| 64 | +## Example 2 |
| 65 | + |
| 66 | +In this example, the `brew_tea` and `make_toast` async functions start running at the same time. `make_toast` finishes first in 3 seconds, while `brew_tea` takes 5 seconds to complete. The program waits for both tasks to finish, then prints their results together after a total of 5 seconds: |
| 67 | + |
| 68 | +```py |
| 69 | +import asyncio |
| 70 | + |
| 71 | +async def brew_tea(): |
| 72 | + print("Start brewing tea") |
| 73 | + await asyncio.sleep(5) # Pauses for 5 seconds |
| 74 | + return "The tea is ready!" |
| 75 | + |
| 76 | +async def make_toast(): |
| 77 | + print("Start making toast") |
| 78 | + await asyncio.sleep(3) # Pauses for 3 seconds |
| 79 | + return "The toast is ready!" |
| 80 | + |
| 81 | +async def make_breakfast(): |
| 82 | + batch = asyncio.gather(brew_tea(), make_toast()) |
| 83 | + tea_complete, toast_complete = await batch |
| 84 | + print(tea_complete) |
| 85 | + print(toast_complete) |
| 86 | + |
| 87 | +result = asyncio.run(make_breakfast()) |
| 88 | +print(result) |
| 89 | +``` |
| 90 | + |
| 91 | +The output of this code is: |
| 92 | + |
| 93 | +```shell |
| 94 | +Start brewing tea |
| 95 | +Start making toast |
| 96 | +The tea is ready! |
| 97 | +The toast is ready! |
| 98 | +None |
| 99 | +``` |
0 commit comments