Is there an official way to add methods to an instance?

Brian Vanderburg II BrianVanderburg2 at aim.com
Fri Apr 4 02:57:56 CEST 2008


I don't know if this is the correct place to send this question.

I've checked out some ways to get this to work.  I want to be able to 
add a new function to an instance of an object.  I've tested two 
different methods that cause problems with 'deleting'/garbage collection 
(__del__ may never get called), but implemented one sort of hackishly 
maybe that works find. I'm wondering if there is more of an official way 
than mine.

1.
import new
import gc

class A:
    def __del__(x):
       print "Deleting"

def f(x):
    print x

a = A()
a.f = new.instancemethod(a,f)
a.f() # This works
del a # Not what is expected
gc.collect() # Works, but __del__ does not get called

2.
import gc

def addmethod(self,func,name):
    def wrapper(*args,**kwargs):
       return func(self,*args,**kwargs)
    setattr(self,name,func)

class A:
    def __del__(x):
       print "Deleting"

def f(x):
    print x

a = A()
addmethod(a, f, "f")
a.f() # Works as expected
del a # nope
gc.collect() # Still __del__ doesn't get called

3. Slightly hackish method, maybe some problems
import gc
import weakref

def addmethod(self,func,name):
    # change the value of 'self' so wrapper.func_globals will reference 
the new value
    self = weakref.ref(self)
    def wrapper(*args,**kwargs):
       return func(self(),*args,**kwargs)
    setattr(self(),name,func)

class A:
    def __del__(x):
       print "Deleting"

def f(x):
    print x

a = A()
addmethod(a, f, "f")
a.f() # Works as expected
del a
gc.collect()

With this method 'del a' does the expected most of the time, and 
"Deleting" does get printed or when calling 'gc.collect()' it prints 
correctly.  This seems the best approach so that when 'a' is no longer 
valid, the object can die instead of continuing to exitng because 
wrapper.func_globals still contains a reference, but seems very hackish 
an maybe problematic.  I'm wondering if there is a better way?

Brian Vanderburg II






More information about the Python-list mailing list