How to bound a method to a instance ?

"Martin v. Löwis" martin at v.loewis.de
Wed Feb 11 12:30:27 EST 2004


Maarten van Reeuwijk wrote:
> Thank you emmanuel for asking this question, I was wondering exactly the
> same thing. Is it also possible to override the reload method to make it
> (besides reloading) to scan through all namespaces for objects of class
> toto.toto and replace their methods automatically? What would that code
> look like?

In general, it is impossible or atleast very inefficient to do that.
It may be easiest if toto.toto would prepare itself for reloading:

import weakref
try:
   weakref.totos
except AttributeError:
   weakref.totos = []

class toto:
   def __init__(self, args):
     weakref.totos.append(weakref.ref(self))
     ...

def update_totos():
   for t in weakref.totos:
     t = t()
     if t: t.__class__ = toto

def shrink_totos():
   totos = []
   for t in weakref.totos:
     if t(): totos.append(t)
   weakref.totos=[]

Then, after reloading toto, invoke toto.update_totos(). From
time to time, invoke weakref.shrink_totos(), to discard unused
weak references.

If you absolutely want to update all objects without preparing
a list earlier, you can use gc.get_objects() to find all containers;
you need to find out which of those are totos. Don't compare the
classes of the objects for identity (o.__class__ is toto.toto), unless
you have a reference of the old class (i.e. before reloading).

Regards,
Martin




More information about the Python-list mailing list