Include suggestions from Nick Coghlan.
This commit is contained in:
parent
787d7a1050
commit
235d1d29e2
27
pep-0343.txt
27
pep-0343.txt
|
@ -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
|
||||
|
|
Loading…
Reference in New Issue