Friday 30 November 2007

"@apply antipattern" or "Python doesn't need a with_statement!"

Remember the new funky open syntax?

with open("somefile","r") as f:
print f.readlines()
It looks very pretty and ensures that the file gets closed after usage. Neat. However, nothing stops us from writing a decorator that does similar job without importing from __future__:
def opened(*args):
def decorator(function):
def ret():
f = open(*args)
try:
function(f)
finally:
f.close()
return ret
return decorator
I know what it looks like. Even though, it makes us able to write simply:
@opened("file.txt", "r")
def do_it(f):
print f.readlines()
do_it()
or even:
@apply 
@opened("file.txt", "r")
def do_it(f):
print f.readlines()
You see now why Guido doesn't like functional programming.

No comments: