Hooks (Re: What does Python fix?)

hungjunglu hungjunglu at yahoo.com
Tue Jan 22 01:56:34 EST 2002


--- In python-list at y..., "Andrew Dalke" <dalke at d...> wrote:
> 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.  

I explicitly said IT IS POSSIBLE in Python. :)

#------------------------------
import new

class A:
    def f(self, x):
        print 'multiply by 2'
        return 2*x

def g(self, x):
    print 'add 1 before calling'
    y = self.f_old(x+1)
    print 'add 1 after calling'
    return y+1

a = A()

print '----- old implementation: input=1'
z = a.f(1)
print 'result =', z

A.f_old = A.f
A.f = new.instancemethod(g, None, A)

print '----- new implementation: input=1'
z = a.f(1)
print 'result =', z

#------------------------------
output:

----- old implementation: input=1
multiply by 2
result = 2
----- new implementation: input=1
add 1 before calling
multiply by 2
add 1 after calling
result = 5

#------------------------------

(I use Python 2.1. I have not checked the situation in 2.2.) Anyway, 
the goal is to be able to intercept function/method calls 
dynamically, after the function/method has been written, and without 
creating new wrapper classes. Being able to insert hooks dynamically 
is very useful. I hope I have been more clear.

regards,

Hung Jung






More information about the Python-list mailing list