dinamically altering a function
Jeremy Bowers
jerf at jerf.org
Sat Mar 12 18:01:34 EST 2005
> What i want is to declare in the decorator some code that is common to all
> these functions, so the functions assume that the decorator will be there
> and wont need to duplicate the code provided by it, and the functions are
> not known ahead of time, it has to be dynamic.
This sounds like a call for a Pythonic varient on the Template pattern:
class Root(object):
def __init__(self):
self.dataChunk = 22 # or whatever
class Child(Root):
def __call__(self):
print self.dataChunk
>>> c = Child()
>>> c()
22
Don't be put off by the "OO"-ness here, it acts just like a function
thanks to __call__, and behind the scenes you get full OO support for your
functions.
I strongly suspect this is the best solution to your problem, not a
decorator. Note whatever you are doing to create the functions can be done
in other ways, especially note that "class" statements are executed, not
declarations, for instance:
>>> import operator
>>> class Root(object):
... def __init__(self):
... self.op1 = 22
... self.op2 = 44
...
>>> funcs = []
>>> for op in operator.add, operator.sub, operator.pow:
... def newfunc(self, basefunc = op):
... print basefunc(self.op1, self.op2)
... class New(Root):
... __call__ = newfunc
... funcs.append(New)
...
>>> funcs # show the classes
[<class '__main__.New'>, <class '__main__.New'>, <class '__main__.New'>]
>>> [x() for x in funcs] # show the new "functions"
[<__main__.New object at 0xb7e78bcc>, <__main__.New object at 0xb7e78e4c>, <__ma
in__.New object at 0xb7e78ecc>]
>>> [x()() for x in funcs] # call each of the functions, note no return
66
-22
116572995441436549620289361494791139391860487905922101805056
[None, None, None]
Upshot is, with a bit of creativity this can do whatever you want, in
conjection with dynamically-created classes, no bytecode hacks, no really
weird decorators, just standard OO and __call__.
More information about the Python-list
mailing list