पाठ 49 / 49

एसिंक की मूल बातें

Threads के बिना async, await और asyncio से I/O-bound काम concurrently चलाएँ।

async क्यों?

async/await किसी प्रोग्राम को किसी काम के इंतज़ार में (जैसे नेटवर्क जवाब) दूसरे काम करने देते हैं, बजाय सब कुछ रोक देने के।

एक न्यूनतम उदाहरण

async def फ़ंक्शन एक कोरूटीन है। await इसे किसी धीमी संक्रिया पर रोकता है; asyncio.run पूरी चीज़ शुरू करता है।

import asyncio

async def fetch_data(name, delay):
    print(f"{name}: starting")
    await asyncio.sleep(delay)   # simulate I/O wait
    print(f"{name}: done")

async def main():
    await asyncio.gather(
        fetch_data("A", 2),
        fetch_data("B", 1),
    )

asyncio.run(main())

Output:

A: starting
B: starting
B: done
A: done

अंतिम क्विज़ 1/8

अंतिम क्विज़

त्वरित जाँच: कौन-सा type immutable है?

  • list
  • dict
  • tuple
  • set
Answer

tuple — Tuples बनाने के बाद बदले नहीं जा सकते।

अंतिम क्विज़ 2/8

अंतिम क्विज़

त्वरित जाँच: `[n*n for n in range(4)]` क्या बनाता है?

  • [1, 4, 9, 16]
  • [0, 1, 2, 3]
  • [0, 2, 4, 6]
  • [0, 1, 4, 9]
Answer

[0, 1, 4, 9] — range(4) 0..3 देता है और हर एक का वर्ग होता है।

अंतिम क्विज़ 3/8

अंतिम क्विज़

त्वरित जाँच: `def f(x, items=[])` से क्यों बचें?

  • The list is created once and shared across calls
  • It is a syntax error
  • It is slower
  • It cannot be called
Answer

The list is created once and shared across calls — Mutable defaults calls के बीच बने रहते हैं; None या factory उपयोग करें।

अंतिम क्विज़ 4/8

अंतिम क्विज़

त्वरित जाँच: `with open(...) as f:` क्या सुनिश्चित करता है?

  • The file is encrypted
  • The file is closed even if an error occurs
  • The file is created
  • The file is read-only
Answer

The file is closed even if an error occurs — Context managers cleanup अपने-आप चलाते हैं।

अंतिम क्विज़ 5/8

अंतिम क्विज़

त्वरित जाँच: Function में `yield` क्या करता है?

  • Ends the program
  • Raises an exception
  • Produces a value lazily and pauses the function
  • Returns a list
Answer

Produces a value lazily and pauses the function — Generators अगली call पर वहीं से चलते हैं जहाँ रुके थे।

अंतिम क्विज़ 6/8

अंतिम क्विज़

त्वरित जाँच: कौन-सा decorator alternate constructor बनाता है?

  • @staticmethod
  • @property
  • @dataclass
  • @classmethod
Answer

@classmethod — Classmethod cls पाता है और नया instance लौटा सकता है।

अंतिम क्विज़ 7/8

अंतिम क्विज़

त्वरित जाँच: कौन-सा keyword coroutine शुरू करता है?

  • async def
  • yield def
  • lambda
  • class
Answer

async def — `async def` ऐसा coroutine बनाता है जिसे await किया जा सकता है।

अंतिम क्विज़ 8/8

अंतिम क्विज़

त्वरित जाँच: कौन-सा tool project के packages अलग करता है?

  • os
  • venv
  • sys
  • math
Answer

venv — Virtual environment हर project की dependencies अलग रखता है।