Decorator Base Class: Needs improvement.
Ron_Adam
radam2 at tampabay.rr.com
Mon Apr 4 17:49:18 EDT 2005
Ok, that post may have a few(dozen?) problems in it. I got glitched
by idles not clearing variables between runs, so it worked for me
because it was getting values from a previous run.
This should work better, fixed a few things, too.
The decorators can now take more than one argument.
The function and arguments lists initialize correctly now.
It doesn't work with functions with more than one variable. It seems
tuples don't unpack when given to a function as an argument. Any way
to force it?
class Decorator(object):
"""
Decorator - A base class to make decorators with.
self.function - name of function decorated.
self.arglist - arguments of decorator
self.preprocess - over ride to preprocess function arguments.
self.postprocess - over ride to postprocess function
return value.
Example use:
class mydecorator(Decorate):
def self.preprocess(self, args):
# process args
return args
def self.postprocess(self, results):
# process results
return results
deco = mydecorator()
@deco
def function(args):
# function body
return args
"""
def __init__(self):
self.function = None
self.arglist = []
def __call__(self, *arg):
if len(arg) == 1:
arg = arg[0]
self.arglist.append(arg)
def _wrapper( *args):
if len(args) == 1:
args = args[0]
pre_args = self.preprocess(args)
result = self.function(pre_args)
return self.postprocess(result)
if 'function' in str(arg):
self.arglist = self.arglist[:-1]
self.function = arg
return _wrapper
return self
def preprocess(self, args):
return args
def postprocess(self, result):
return result
#---3---
class mydecorator(Decorator):
def preprocess(self, args):
args = 2*args
return args
def postprocess(self, args):
args = args.upper()
args = args + str(self.arglist[0])
return args
deco = mydecorator()
@deco('xyz')
def foo(text):
return text
print foo('abc')
#---2---
class decorator2(Decorator):
def preprocess(self, args):
return args+sum(self.arglist[0])
def postprocess(self, args):
return args
deco2 = decorator2()
@deco2(1,2)
def foo(a):
return a
print foo(1)
# This one doesn't work yet.
#---3---
class decorator3(Decorator):
pass
deco3 = decorator3()
@deco3
def foo(a,b):
return a,b
print foo(1,3)
More information about the Python-list
mailing list