Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rewrite consecutive 'async with' statements into a loop?

I have the following excerpt which works fine in every regard except that it requires that I know how many WebSockets I plan to open in advance.

If instead I started with a list of hosts and had to create N WebSocket connections, how could I accomplish what this code does for 3 Websockets (via 'async with') for N in a loop?

The awaiting I already have in a loop, it's the "async with" that I cannot figure out how to "loopify".

async with websockets.connect('ws://192.168.0.174:81') as websocket1:
    async with websockets.connect('ws://192.168.0.194:81') as websocket2:
        async with websockets.connect('ws://192.168.0.179:81') as websocket3:

            datatosend = GetBallData()

            for socket in [websocket1, websocket2, websocket3]:
                await socket.send(datatosend)
like image 503
Dave Avatar asked Oct 18 '18 23:10

Dave


1 Answers

Starting from Python3.7 there is AsyncExitStack available in contextlib module, this is how it can be used for your issue:

hosts = ['ws://192.168.0.174:81', 'ws://192.168.0.194:81', 'ws://192.168.0.179:81']
async with contextlib.AsyncExitStack() as stack:
    sockets = [
        await stack.enter_async_context(websockets.connect(host))
        for host in hosts
    ]
like image 186
sanyassh Avatar answered Nov 04 '22 09:11

sanyassh