How to use await inside map function

Viewed 1955

I have the following code

async def foo():
   some_tuple = tuple(map(bar, some_tuple))
async def bar(data):
   # Await another function and do some other stuff
   return something

Since bar is async it must be awaited. However, I am unsure where to await bar. I tried awaiting it inside map, I tried awaiting map, I tried awaiting tuple and nothing worked.

How do I await bar inside map?

1 Answers

You can't use map with async functions since map is synchronous and doesn't suspend execution inside the loop. The same applies to the tuple constructor which expects a synchronous generator.

Ti fix this, you can replace the map/tuple pair with a list comprehension, which can be async, and readily converted to tuple:

some_tuple = tuple([await fn(elem) for elem in iterable])

Another option is to use the async versions of map and tuple from the asyncstdlib package, which also provides a lot of additional and useful functionality:

import asyncstdlib.builtins.map as amap
import asyncstdlib.builtins.tuple as atuple

some_tuple = await atuple(amap(fn, iterable))
Related