run time code generation in python

Terry Reedy tjreedy at udel.edu
Thu Oct 9 12:21:09 EDT 2003


"Carlo v. Dango" <amigo at fake.not> wrote in message
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 have tried the
compile(str)
> method but I haven't succeeded.

compile() gives you a code object;
you probably want 'exec string' to get a function in the current
namespace

>>> exec "def g(): print 'g defined' "
>>> g()
g defined

or follow other responder's advice...

Terry J. Reedy






More information about the Python-list mailing list