What is the python “with” statement designed for?

后端 未结 10 1842
心在旅途
心在旅途 2020-11-21 07:52

I came across the Python with statement for the first time today. I\'ve been using Python lightly for several months and didn\'t even know of its existence! G

10条回答
  •  [愿得一人]
    2020-11-21 07:59

    Another example for out-of-the-box support, and one that might be a bit baffling at first when you are used to the way built-in open() behaves, are connection objects of popular database modules such as:

    • sqlite3
    • psycopg2
    • cx_oracle

    The connection objects are context managers and as such can be used out-of-the-box in a with-statement, however when using the above note that:

    When the with-block is finished, either with an exception or without, the connection is not closed. In case the with-block finishes with an exception, the transaction is rolled back, otherwise the transaction is commited.

    This means that the programmer has to take care to close the connection themselves, but allows to acquire a connection, and use it in multiple with-statements, as shown in the psycopg2 docs:

    conn = psycopg2.connect(DSN)
    
    with conn:
        with conn.cursor() as curs:
            curs.execute(SQL1)
    
    with conn:
        with conn.cursor() as curs:
            curs.execute(SQL2)
    
    conn.close()
    

    In the example above, you'll note that the cursor objects of psycopg2 also are context managers. From the relevant documentation on the behavior:

    When a cursor exits the with-block it is closed, releasing any resource eventually associated with it. The state of the transaction is not affected.

提交回复
热议问题