adding methods at runtime and lambda

James Stroud jstroud at mbi.ucla.edu
Thu May 3 16:21:54 EDT 2007


Mike wrote:
> 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.
> 

You don't absolutely require lambda.

def add_self(afun):
   def _f(self, *args, **kwargs):
     return afun(*args, **kwargs)
   return _f

superdict = addm(dict(), add_self(myUtils.HasDrive), "hasdrive")

James



More information about the Python-list mailing list