Interview question
How do you write and run coroutines with async/await in Python? Python में async/await से coroutines कैसे लिखें और चलाएं?
Answer
import asyncio
# Defining a coroutine function
async def greet(name):
print(f'Hello, {name}')
await asyncio.sleep(1) # simulates async work (I/O wait)
print(f'Goodbye, {name}')
return f'{name} greeted'
# Calling a coroutine function WITHOUT await just creates a coroutine object,
# it does NOT run the code yet
coro = greet('John')
print(coro) # <coroutine object greet at 0x...>
# Need to actually run it via asyncio.run() or await inside another coroutine
# Running the top-level coroutine
asyncio.run(greet('John'))
# Running multiple coroutines CONCURRENTLY with gather
async def main():
results = await asyncio.gather(
greet('Alice'),
greet('Bob')
)
print(results) # ['Alice greeted', 'Bob greeted']
asyncio.run(main())
# Creating tasks explicitly for finer control (starts running immediately)
async def main2():
task1 = asyncio.create_task(greet('Task1'))
task2 = asyncio.create_task(greet('Task2'))
# both tasks are now scheduled and running concurrently
await task1
await task2
asyncio.run(main2())
# Common mistake: forgetting await
async def broken():
greet('Oops') # missing 'await' - coroutine created but never runs!
# RuntimeWarning: coroutine 'greet' was never awaitedimport asyncio
async def greet(name):
print(f'Hello, {name}')
await asyncio.sleep(1)
print(f'Goodbye, {name}')
return f'{name} greeted'
# await के बिना call करने से सिर्फ coroutine object बनता है, चलता नहीं
coro = greet('John')
print(coro) # coroutine object
# Top-level coroutine चलाना
asyncio.run(greet('John'))
# gather से concurrently चलाना
async def main():
results = await asyncio.gather(
greet('Alice'),
greet('Bob')
)
print(results)
asyncio.run(main())
# create_task से tasks बनाना
async def main2():
task1 = asyncio.create_task(greet('Task1'))
task2 = asyncio.create_task(greet('Task2'))
await task1
await task2
asyncio.run(main2())
# Common गलती: await भूलना
async def broken():
greet('Oops') # 'await' missing - कभी नहीं चलेगा!
# RuntimeWarningWas this answer clear?