[Python-Dev] PEP 340: Deterministic Finalisation (new PEP draft, either a competitor or update to PEP 340)
Nick Coghlan
ncoghlan at iinet.net.au
Sat May 7 04:17:44 CEST 2005
PEP 340 contains several different ideas. This rewrite separates them into five
major areas:
- passing data into an iterator
- finalising iterators
- integrating finalisation into for loops
- the new non-looping finalising statement
- integrating all of these with generators.
The first area has nothing to do with finalisation, so it is not included in
this rewrite (Steven Bethard wrote an Enhanced Iterators pre-PEP which covers
only that area, though).
The whole PEP draft can be found here:
http://members.iinet.net.au/~ncoghlan/public/pep-3XX.html
But I've inlined some examples that differ from or aren't in PEP 340 for those
that don't have time to read the whole thing (example numbers are from the PEP):
4. A template that tries something up to n times::
def auto_retry(n=3, exc=Exception):
for i in range(n):
try:
yield
except exc, err:
# perhaps log exception here
yield
raise # re-raise the exception we caught earlier
Used as follows::
for del auto_retry(3, IOError):
f = urllib.urlopen("http://python.org/")
print f.read()
6. It is easy to write a regular class with the semantics of example 1::
class locking:
def __init__(self, lock):
self.lock = lock
def __enter__(self):
self.lock.acquire()
def __exit__(self, type, value=None, traceback=None):
self.lock.release()
if type is not None:
raise type, value, traceback
(This example is easily modified to implement the other examples; it shows that
generators are not always the simplest way to do things.)
8. Find the first file with a specific header::
for name in filenames:
stmt opening(name) as f:
if f.read(2) == 0xFEB0: break
9. Find the first item you can handle, holding a lock for the entire loop, or
just for each iteration::
stmt locking(lock):
for item in items:
if handle(item): break
for item in items:
stmt locking(lock):
if handle(item): break
10. Hold a lock while inside a generator, but release it when returning control
to the outer scope::
stmt locking(lock):
for item in items:
stmt unlocking(lock):
yield item
Cheers,
Nick.
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
---------------------------------------------------------------
http://boredomandlaziness.blogspot.com
More information about the Python-Dev
mailing list