run time code generation in python

Carlo v. Dango ILoveMyAmiga at faker.not
Thu Oct 9 09:28:41 EDT 2003


Duncan Booth <duncan at NOSPAMrcp.co.uk> wrote in
news:Xns940F8FDA1866Cduncanrcpcouk at 127.0.0.1: 

> 
>> 
>> 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 don't see why you need to generate any code at runtime.
> This does the same as your code, only now the name of the function to
> which you are forwarding the call is stored in a variable:
> 
> name = 'foo'
> def foo(self, *args, **kwargs):
>     getattr(self.i, name)(*args, **kwargs)


because there potentially could be many forwarder methods applied the 
instance (forwarding to different methods.. but ofcourse are named 
differently themselves)... hence it would not know where to find its 
name.. hmm.. maybe if the method could somehow find out its own name, it 
would know what to call on the i attribute. Is that possible?

 
> You should be aware that if you store a function in an instance at
> runtime, the magic binding to 'self' won't happen. You either need to

aahh.. ok so i can only store functions and not methods! nice point! hmm 
but in this particular case I'm taking over the handling of self anyway 
so it will not hurt me I think.. except that I have to get hold of the 
attribute i on the instance. So that's why you use getattr() rather than 
self.i 


> store the function in the class, or leave out the self parameter if
> you want to insert it into an instance. Something like this may be
> what you need: 

well I need to insert it in the instance.. but yes I thought about 
inserting the function in the class.. I thought I may be able to insert 
the function during the __init__ execution..

> 
> (I'm assuming you want a bit more in the function definition,
> otherwise of course, 'something.foo=something.i.foo' is an even easier
> solution). 

well, outsiders may not know that there is a forwarding taking place.. 
and I need only this since I have wrapper methods on top of each method 
execution.. or atleast Ive made that using metaclasses.. but this is not 
enough as I've found out I need to operate purely on an instance level..


> All code samples above are untested and therefore almost certainly
> wrong. 

no problem. ;-)


-Carlo 





More information about the Python-list mailing list