函数已使用await仍触发‘coroutine was never awaited’报错的技术咨询
await in Your Async Wrapper Hey there! Let's break down why you're seeing that coroutine was never awaited error, even though you’ve got an await inside your aio_wrapper function.
The Root Cause
Your _aio function returns an async wrapper (aio_wrapper). When you call self._aio(self._client.get_object)(Bucket=self.bucket_name, Key=key), you’re creating a coroutine object—but you never actually tell Python to run this coroutine by using await on it.
The await inside aio_wrapper handles the execution of loop.run_in_executor, but that’s entirely internal to the wrapper. The act of calling the async wrapper itself produces a coroutine that needs to be awaited to get the final result. If you check the type(res) in your current code, you’ll see it’s <class 'coroutine'>—that unexecuted coroutine is exactly what’s triggering the error.
Solutions
1. Await the Coroutine in an Async Function
If your calling code is part of an async context, simply add await when you invoke the wrapped function:
async def process_images(): for key in image_keys: # Add await here to run the coroutine and retrieve the actual result res = await self._aio(self._client.get_object)(Bucket=self.bucket_name, Key=key) print(type(res)) # Now this will show the result type, not a coroutine # Execute your async function asyncio.run(process_images())
2. Batch Process with asyncio.gather (More Efficient)
Since you’re processing multiple objects, using asyncio.gather to run all coroutines concurrently will be much faster than awaiting them one by one:
async def fetch_all_images(): # Create a list of coroutine tasks tasks = [ self._aio(self._client.get_object)(Bucket=self.bucket_name, Key=key) for key in image_keys ] # Run all tasks at once and wait for all results results = await asyncio.gather(*tasks) for res in results: print(type(res)) asyncio.run(fetch_all_images())
Key Takeaway
Async functions return coroutines when called—you must always await those coroutines (or schedule them via an asyncio loop) to execute them. The await inside your wrapper handles a nested async operation, but it doesn’t replace the need to await the wrapper itself.
内容的提问来源于stack exchange,提问作者ziad_dp

