run time code generation in python

Duncan Booth duncan at NOSPAMrcp.co.uk
Thu Oct 9 11:13:37 EDT 2003


"Carlo v. Dango" <ILoveMyAmiga at faker.not> wrote in 
news:Xns940F9DEEABCA26020206 at 172.16.0.1:

>> 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?

That's why my other examples all generated the wrapper function inside 
another function. That way you use the nested scope variables to store 
useful things like the attribute name.

-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list