Include suggestions from Nick Coghlan.

This commit is contained in:
Guido van Rossum 2005-06-02 15:13:55 +00:00
parent 787d7a1050
commit 235d1d29e2
1 changed files with 26 additions and 1 deletions

View File

@ -413,7 +413,9 @@ Optional Extensions
which does not do what one might think (f is closed before BLOCK2
is entered).
OTOH such mistakes are easily diagnosed.
OTOH such mistakes are easily diagnosed; for example, the
with_template decorator above raises RuntimeError when the second
with-statement calls f.__enter__() again.
Open Issues
@ -642,6 +644,29 @@ Examples
methods to the decimal.Context class so that this example can
be simplified to "with decimal.getcontext() as ctx: ...".)
10. A generic "object-closing" template:
@with_template
def closing(obj):
try:
yield obj
finally:
obj.close()
This can be used to deterministically close anything with a
close method, be it file, generator, or something else:
# emulate opening():
with closing(open("argument.txt")) as contradiction:
for line in contradiction:
print line
# deterministically finalize a generator:
with closing(some_gen()) as data:
for datum in data:
process(datum)
References
[1] http://blogs.msdn.com/oldnewthing/archive/2005/01/06/347666.aspx