What is the Python “with” statement used for?

后端 未结 3 1659
半阙折子戏
半阙折子戏 2021-01-03 09:09

I am trying to understand the with statement in python. Everywhere I look it talks of opening and closing a file, and is meant to replace the try-finally block. Could someo

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-03 09:47

    There are twelve examples of using with in PEP343, including the file-open example:

    1. A template for ensuring that a lock, acquired at the start of a block, is released when the block is left
    2. A template for opening a file that ensures the file is closed when the block is left
    3. A template for committing or rolling back a database transaction
    4. Example 1 rewritten without a generator
    5. Redirect stdout temporarily
    6. A variant on opened() that also returns an error condition
    7. Another useful example would be an operation that blocks signals
    8. Another use for this feature is the Decimal context
    9. Here's a simple context manager for the decimal module
    10. A generic "object-closing" context manager
    11. a released() context to temporarily release a previously acquired lock by swapping the acquire() and release() calls
    12. A "nested" context manager that automatically nests the supplied contexts from left-to-right to avoid excessive indentation

提交回复
热议问题