November 15, 2007

python decorators


"""
DECORATORS
PEP 318
Introduced in Python 2.4
"
""

#-----------------------------------------
# simple decorator
#-----------------------------------------
def log(f):
def new_f(*args, **kwargs):
print f.__name__, ': called'
print args, kwargs
f(*args, **kwargs)
print f.__name__, ': end of call'

return new_f

class Simple(object):
@log
def do(self, *args, **kwargs):
print '...done'


#-----------------------------------------
# decorator without sugar
#-----------------------------------------
class NoMagic(object):
def do(self, *args, **kwargs):
print '...done'
do = log(do)


#-----------------------------------------
# decorator with arguments
#-----------------------------------------
def prefix(text):
def fn(method):
def new_fn(*args, **kwargs):
print text,
method(*args, **kwargs)
#rename the method to be the same as the decorated one
#new_fn.__name__ = method.__name__
return new_fn

return fn

class Args(object):
@prefix('wait for it: ')
def do(self, *args, **kwargs):
print '...done'


#-----------------------------------------
# decorator with arguments and no sugar
#-----------------------------------------
class NoMagicArgs(object):
def do(self, *args, **kwargs):
print '...done'
do = prefix('wait for it: ')(do)


#-----------------------------------------
# chaining decorators
#-----------------------------------------
class Chain(object):
@log
@prefix("I'm chaind but still: ")
def do(self, *args, **kwargs):
print '...done'

November 3, 2007

practical common lisp

Peter Seibel's book Practical Common Lisp is a jewel.


The book introduces the reader to Lisp in a gentle way, but also covers most of the features that make Lisp so powerful: macros, multimethods, dynamic variables...


The book is also filled with historical notes that make for a very interesting read.
Towards the end of the book, entire chapters are devoted to building small apps, justifying the title.


The book taught me about Lisp, but also taught me about OO (sic) and about what a modern programming language should provide. Five stars.