Tuesday, May 17, 2005

Anonymous blocks (PEP 340)

PEP (Python Enhancement Proposal) 340 suggests adding a new block construct to the Python language which would "provide a mechanism for encapsulating patterns of structure". I don't understand the details of the whole proposal just yet, but it looks like the point is making it simpler to execute a blocks of code between other steps, without having to put all the other steps into the code individually. For example, from the PEP, a way to execute some commands while a file is open and guarantee it will be closed when done:
def opening(filename, mode="r"):
f = open(filename, mode)
try:
yield f
finally:
f.close()

Used as follows:
block opening("/etc/passwd") as f:
for line in f:
print line.rstrip()

Or to retry something several times:
def auto_retry(n=3, exc=Exception):
for i in range(n):
try:
yield None
return
except exc, err:
# perhaps log exception here
continue
raise # re-raise the exception we caught earlier

Used as follows:
block auto_retry(3, IOError):
f = urllib.urlopen("http://python.org/peps/pep-0340.html")
print f.read()

This seems to me to be trying to solve a problem long ago solved by Lisp's macros, which coincidentally also solve a plethora of other problems unaddressed by the proposed block facility. I'm happy to say Noodle should never need block. (Of course, if a programmer does need it, she can implement it as a macro pretty quickly!)

I see more and more how the capability of extending Lisp's syntax has made it so powerful and so capable of remaining competetive after being around for 50 years.

0 comments: