run time code generation in python

Ian Bicking ianb at colorstudy.com
Thu Oct 9 11:25:03 EDT 2003


On Thursday, October 9, 2003, at 07:21 AM, Carlo v. Dango wrote:
> Hello there. I have found a need to runtime generate a method and 
> instert
> it into an object instance. The code is a simple forwarding mechanism 
> like
>
> def foo(self, *args, **kwargs):
>     self.i.foo(*args, **kwargs)

> method.. however, it is only at runtime that I know the name "foo" so I
> cannot gerenate such a method any sooner. I have tried the compile(str)
> method but I haven't succeeded. I've tried using the __getattribute__ 
> but
> there is a problem in that I do not know if __getattribute__ was 
> called due
> to a method call taking place, or due to someone who just wants a 
> reference
> to a method.. (and for other reasons as well :) I need to runtime 
> generate
> the above method.

__getattr__ will allow you to forward all the methods you don't want to 
override.  So you can do:

class OverridingProxy:
     def __init__(self, obj):
         self.obj = obj
     def overridedMethod(self, foo, bar):
         # ... custom implementation
     def __getattr__(self, attr):
         return getattr(self.obj, attr)

You don't need to distinguish between methods and normal attributes, 
generally.  If you do (e.g., you want to filter the output of all the 
methods) you'll have to check the type of the getattr() result, and 
create a second proxy if it's a method.  (That proxy would take the 
method reference as the object to wrap, and would implement __call__)

--
Ian Bicking | ianb at colorstudy.com | http://blog.ianbicking.org






More information about the Python-list mailing list