← Back to Python Course | Chapter 11: Advanced Python | Lesson 7 of 12

Python async और await

async और await किसी program को कोई धीमा काम शुरू करके इंतज़ार करते समय बाकी काम करने देते हैं, जैसे toaster में ब्रेड डालकर उसके टोस्ट होने तक juice डालना। यह programs को खाली बैठे रहने से रोकता है।
Syntax
python
import asyncio

async def coroutine_name():
    result = await other_coroutine()
    return result

asyncio.run(coroutine_name())

Asynchronous Programming क्या है?

Asynchronous programming एक single thread को कई I/O-bound operations -- network calls, file reads, database queries -- को बिना किसी एक पर block हुए संभालने देती है।

जब एक task किसी धीमे response का इंतज़ार करता है, तो Python का event loop दूसरे तैयार tasks चलाने पर switch कर जाता है, जो उसी काम के लिए threads शुरू करने से कहीं सस्ता है।

उदाहरण: What is Asynchronous Programming?

python
import asyncio

async def main():
    print("Doing work without blocking a thread")

asyncio.run(main())  # runs the coroutine on the event loop

async से Coroutines Define करना

किसी function definition के आगे async लगाना उसे coroutine बना देता है: उसे call करना तुरंत body नहीं चलाता, यह एक coroutine object लौटाता है जिसे वाकई चलने के लिए await या schedule करना ज़रूरी है।

यह अंतर beginners को उलझाता है जो async def functions से सामान्य functions जैसा व्यवहार उम्मीद करते हैं।

उदाहरण: Defining Coroutines with async

python
async def greet():
    return "hello"

coro = greet()  # calling it doesn't run the body, just returns a coroutine object
print(type(coro))
coro.close()  # closes without running the coroutine's body

await से Coroutines का इंतज़ार करना

await keyword current coroutine को उस बिंदु पर रोक देता है और जब तक awaited operation पूरा नहीं हो जाता, control event loop को वापस दे देता है, फिर ठीक वहीं से resume करता है जहाँ छोड़ा था।

आप await को सिर्फ़ किसी दूसरे async def function के अंदर इस्तेमाल कर सकते हैं -- इसे सामान्य code के top level पर इस्तेमाल करना एक syntax error है।

उदाहरण: Awaiting Coroutines with await

python
import asyncio

async def get_value():
    await asyncio.sleep(0)  # pauses here and hands control back to the event loop
    return 42

async def main():
    value = await get_value()  # waits for get_value to complete
    print(value)

asyncio.run(main())

Coroutines चलाना

asyncio.run() किसी synchronous script के लिए standard entry point है: यह एक नया event loop बनाता है, दिए गए coroutine को पूरा होने तक चलाता है, और बाद में उस loop को साफ़-सुथरे तरीके से बंद कर देता है।

इसे आमतौर पर आपके program के बिल्कुल top level पर सिर्फ़ एक बार call किया जाना चाहिए।

उदाहरण: Running Coroutines

python
import asyncio

async def main():
    print("Started with asyncio.run()")

asyncio.run(main())  # creates an event loop, runs main(), then shuts it down

Concurrent Tasks चलाना

asyncio.gather() कई coroutines लेता है, उन्हें event loop पर concurrently चलने के लिए schedule करता है, और सभी के पूरा होने पर उनके results एक साथ लौटाता है।

async code से असली speedup पाने का यही तरीका है -- coroutines को एक-एक करके क्रम में await करने से आपको कोई concurrency फ़ायदा नहीं मिलता।

उदाहरण: Running Concurrent Tasks

python
import asyncio

async def task(n):
    await asyncio.sleep(0)
    return n * 2

async def main():
    results = await asyncio.gather(task(1), task(2), task(3))  # runs all three concurrently
    print(results)

asyncio.run(main())
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.