run time code generation in python

Duncan Booth duncan at NOSPAMrcp.co.uk
Thu Oct 9 09:12:10 EDT 2003


"Carlo v. Dango" <amigo at fake.not> wrote in
news:Xns940F929A63B436020206 at 172.16.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)

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

def forwarder(obj, name):
    def fwd(*args, **kwargs):
        getattr(obj.i, name)(*args, **kwargs)
    return fwd

something.foo = forwarder(something, 'foo')
something.foo(42) # Calls something.i.foo(42)

Alternatively:

def forwarder(obj, name):
    def fwd(*args, **kwargs):
        getattr(obj, name)(*args, **kwargs)
    return fwd

something.foo = forwarder(something.i, 'foo')
something.foo(42) # Calls something.i.foo(42)

(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).

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

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