[Python] Create a "with" block on several context managers? [duplicate]

Discussão em 'Python' iniciado por Stack, Fevereiro 17, 2025.

  1. Stack

    Stack Membro Participativo

    Suppose you have three objects you acquire via context manager, for instance A lock, a db connection and an ip socket. You can acquire them by:

    with lock:
    with db_con:
    with socket:
    #do stuff


    But is there a way to do it in one block? something like

    with lock,db_con,socket:
    #do stuff


    Furthermore, is it possible, given an array of unknown length of objects that have context managers, is it possible to somehow do:

    a=[lock1, lock2, lock3, db_con1, socket, db_con2]
    with a as res:
    #now all objects in array are acquired


    If the answer is "no", is it because the need for such a feature implies bad design, or maybe I should suggest it in a pep? :p

    Continue reading...

Compartilhe esta Página