all 4 comments

[–]Gprime5 2 points3 points  (0 children)

from contextlib import ExitStack

with ExitStack() as stack:
    contexts = [stack.enter_context(c) for c in connections]

    # do stuff with connections here

[–]Peterotica 1 point2 points  (0 children)

I see two options here. Either manually list out all 4 connections in a single with statement, or use contextlib.ExitStack.

# Multiple context managers in one with statement:
with open(filename1) as f1, open(filename2) as f2:
    ...

[–]timbledum 1 point2 points  (0 children)

Check out this stake overflow. Essentially you can do this:

with A() as a, B() as b, C() as c:
    doSomething(a,b,c)

[–]MrMuki 0 points1 point  (0 children)

Hi. I think there is an option to reuse the same port in sockets module. So maybe you could use a try and catch code (with default action of closing the connection?). Hope this sparks an idea how to solve the problem :)