import asyncio
import inspect
import dis
asyncdefexample():
await asyncio.sleep(0)
return42# Coroutine object
coro = example()
print(f"Type: {type(coro)}")
print(f"Is coroutine: {inspect.iscoroutine(coro)}")
print(f"State: {inspect.getcoroutinestate(coro)}")
# Must close or run it
coro.close()
# Bytecodeprint(f"\nBytecode:")
dis.dis(example)
# async def compiles similarly to regular def# but the code object has CO_COROUTINE flagprint(f"\nFlags: {example.__code__.co_flags}")
print(f"Is coroutine func: {inspect.iscoroutinefunction(example)}")
Output
Click "Run" to execute your code
async def sets the CO_COROUTINE flag on the code object. The bytecode uses GET_AWAITABLE and SEND to implement await. Coroutine objects track their state (created, running, suspended, closed).
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?