run time code generation in python

Carlo v. Dango ILoveMyAmiga at faker.not
Thu Oct 9 17:26:43 EDT 2003


Ian Bicking <ianb at colorstudy.com> wrote in
news:mailman.1065713223.23716.python-list at python.org: 

> 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__)

thanks for your posting, but I cannot use your suggestion as mentioned
in my posting. The reason is that I want to redefine self. Hence self
may be changed when a method call is performed.. but i don't know when
method calls are performed.. the getattr is no good since it will not
distinguish between method calls and people only fetching a pointer to
the method. 

-Carlo




More information about the Python-list mailing list