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

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Apr 3 22:06:44 EDT 2008


En Thu, 03 Apr 2008 21:57:56 -0300, Brian Vanderburg II  
<BrianVanderburg2 at aim.com> escribió:

> 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

O thou of little faith, wherefore didst thou doubt?
This is the simplest and preferred way, and it works!
It's true that there is a reference cycle between a and a.f, but the  
garbage collector is able to detect it and dispose of those objects  
*UNLESS* any of them contains a __del__ method written in Python. See  
http://docs.python.org/ref/customization.html
So this *is* the right way, and the object `a` would have been deleted if  
you had not tried to witness the deletion itself... You perturbed the  
system in a non trivial way just by attempting to observe it - isn't this  
Quantum Mechanics applied to Python programming?

We need a side-effect triggered by __del__ but written in C... hmmm, what  
about flushing a file buffer?

py> import new
py> import gc
py> import os
py>
py> class myfile(file): # just to be able to add attributes
...     pass
...
py> def f(x):
...     print x
...
py> a = myfile("a.aaa","w")
py> print os.stat("a.aaa").st_size # 0
0
py> a.f = new.instancemethod(f, a)
py> a.f() # This works
<open file 'a.aaa', mode 'w' at 0x00A293F8>
py> a.write("X") # a single char, should stay on write buffer
py> print os.stat("a.aaa").st_size # still 0
0
py> del a
py> print os.stat("a.aaa").st_size # still 0
0
py> gc.collect()
3
py> print os.stat("a.aaa").st_size # now 1
1

-- 
Gabriel Genellina




More information about the Python-list mailing list