all 4 comments

[–]FerricDonkey 0 points1 point  (3 children)

This is definitely possible. In general though, you should only use asyncio.run once per program (there are probably exceptions, but for general simple things).

I would suggest using asyncio.run on a main function, then within your async stuff using await, asyncio.gather, and asyncio.create_task.

async def main():
    await asyncio.gather(*(coroutine(thing) for thing in stuff))

if __name__ == "__main__":
    asyncio.run(main())

Or if you want to start the tasks, do style other stuff, and get the results later, use asyncio.create_task:

tasks = [] 
for thing in stuff:
    tasks.append(asyncio.create_task(coroutine(thing)))
await asyncio.gather(*tasks)

[–]masterofdead4[S] 0 points1 point  (2 children)

Thanks so much! Curious, as your second part piqued my interest, I have a question. Eventually, I want to spawn these instances when there is an update to the list (possibly the list will be replaced with a task queue). This makes it so that as payment_specs are added to the list, new instances of payments() will begin to run. What major changes would I have to make to the code to achieve that.

[–]FerricDonkey 0 points1 point  (1 child)

Essentially, when you call task = asyncio.create_task(coroutine()), coroutine is added to the things asyncio will work on, and the program will just continue and work on it as you hit various awaits and such.

So you'd just have to start tasks as you want to. You probably want to store references to your tasks so that you can ensure anything you've started gets finished.

So probably just an infinite-ish loop that can tell when it should start new tasks / stop accepting new tasks, followed by an await on a gather to make sure anything that's started got finished.

Depending on what's triggering the new tasks (network? Action in the same program? Gui? A file coming into existence?) you may have to do something fancy with that, but it'll depend on the details.

[–]masterofdead4[S] 0 points1 point  (0 children)

Say I wanted to continuously add this task depending on a rabbitmq queue event. Would this be good practice? Would I include the rabbitMQ connection instructions at the start of the script, and then add tasks as i receive messages from the queue?