What is the python “with” statement designed for?

后端 未结 10 1837
心在旅途
心在旅途 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:57

    I would suggest two interesting lectures:

    • PEP 343 The "with" Statement
    • Effbot Understanding Python's "with" statement

    1. The with statement is used to wrap the execution of a block with methods defined by a context manager. This allows common try...except...finally usage patterns to be encapsulated for convenient reuse.

    2. You could do something like:

    with open("foo.txt") as foo_file:
        data = foo_file.read()
    

    OR

    from contextlib import nested
    with nested(A(), B(), C()) as (X, Y, Z):
       do_something()
    

    OR (Python 3.1)

    with open('data') as input_file, open('result', 'w') as output_file:
       for line in input_file:
         output_file.write(parse(line))
    

    OR

    lock = threading.Lock()
    with lock:
        # Critical section of code
    

    3. I don't see any Antipattern here.
    Quoting Dive into Python:

    try..finally is good. with is better.

    4. I guess it's related to programmers's habit to use try..catch..finally statement from other languages.

提交回复
热议问题