"""
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 15, 2007
python decorators
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment