Can I use or create a task around python’s async/a...
# ask-community
j
Can I use or create a task around python’s async/await? Such that I can do multiple IO things in single task parallel?
1
I suppose I could just always call
run_until_complete
on the loop right? But can I also use the async initializers?
__aenter__
k
Hey @Joël Luijmes, Check out these two threads on this topic - I think they'll be informative!
j
Okay great, I think I know enough 🙂 just doing in the task should work then
👍 1
Okay, just made wrapper which calls context methods
Copy code
class AsyncTask(Task):
    def run(self):
        return asyncio.run(self._bootstrap_run_async())

    @abc.abstractclassmethod
    async def run_async(self):
        raise NotImplementedError('Abstract method')

    async def _bootstrap_run_async(self):
        if self.__aenter__:
            await self.__aenter__()

        hit_except = False
        try:
            return await self.run_async()
        except Exception:
            hit_except = True
            if not self.__aexit__ or not await self.__aexit__(*sys.exc_info()):
                raise
        finally:
            if self.__aexit__ and not hit_except:
                await self.__aexit__(None, None, None)
e
Hi! How this could be applied in practice?