I was messing around with adding methods to a class instance at runtime and saw the usual code one finds online for this. All the examples I saw say, of course, to make sure that for your method that you have 'self' as the first parameter. I got to thinking and thought "I have a lot of arbitrary methods in several utility files that I might like to add to things. How would I do that?" And this is what I came up with:
def AddMethod(currObject, method, name = None): if name is None: name = method.func_name class newclass(currObject.__class__):pass setattr(newclass, name, method) return newclass() And lets say I have a utility function that can check if a drive exists on my windows box called HasDrive. I can add that like this: superdict = addm(dict(), lambda self, d: myUtils.HasDrive(d), "hasdrive") and then I can call superdict.HasDrive('c') lambda makes it possible to add any random function because you can use it to set self as the first parameter. I've found several real uses for this already. My big question is, will something like this be possible in python 3000 if lambda really does go away? I've not heard much about lambda, reduce, etc. lately but I know Guido wanted them out of the language. Is there a better way to do this today than to use lambda? It seemed the simplest way to do this that I could find. -- http://mail.python.org/mailman/listinfo/python-list