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
I would suggest two interesting lectures:
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.