Hooks (Re: What does Python fix?)
Andrew Dalke
dalke at dalkescientific.com
Mon Jan 21 18:28:22 EST 2002
Hung Jung Lu:
>What doesn't Python fix? Hmm... as far as hooks are concerned, I often
>wish there were a simpler way of inserting hooks into pre-existing
>functions/methods more easily. That is, given a function/method f(),
>it would be nice to be able to insert pre-functions and
>post-functions.
I believe you refer to modifing a function in-place, so that existing
references to that function are modified. That indeed is hard, or
even impossible in Python. However, if you just want to do function
composition you can do
class MultiCall:
def __init__(self, f, g):
self.f = f
self.g = g
def __call__(self, *args, **kwargs):
return self.f(self.g(*args, **kwargs))
def __mul__(self, g):
return MultiCall(self, g)
class Function:
def __init__(self, f):
self.f = f
def __call__(self, *args, **kwargs):
return self.f(*args, **kwargs)
def __mul__(self, g):
return MultiCall(self, g)
>>> cos = Function(math.cos)
>>> sin = Function(math.sin)
>>> f = cos * sin
>>> f(0)
1.0
>>> f(math.pi/2)
0.54030230586813977
>>> math.cos(math.sin(math.pi/2))
0.54030230586813977
>>>
To show the composition is done in the right order
>>> math.sin(math.cos(math.pi/2))
6.123233995736766e-17
>>>
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list