how can I execute a function string

Rajarshi Guha rajarshi at
Wed Jan 14 15:25:28 CET 2004

On Mon, 12 Jan 2004 21:23:20 -0500, Francis Avila wrote:

> Rajarshi Guha wrote in message ...
>>Hi ,
>> I have some code that generates a function on the fly in a string.
>>At a later point in time I want to execute this function (which also
>>requires a parameters to be passed to it). So the code is something like
> If you're very ambitious, you can generate an AST tree and compile that:
> see the compile module.  In this simple case there's no advantage,
> however.
> I'll have to think about how to turn the raw source of a function
> definition into a callable.  I'm not sure it's possible in a 100%
> reliable manner. Here's a first attempt (untested):
> def makecallable(source):
>     """Return a function from string source.
>     'def <funcname>' must be the first tokens in source!
>     """
>     co = compile(source, '<makecallable()>', 'single') funcname =
>     co.co_varnames[0] #This is VERY brittle!! fakelocals = {} exec co in
>     globals(), fakelocals
>     return fakelocals[funcname]

Well I was playing with Andrews curves which allows one to visualize a
vector of numbers in terms of a Fourier series. So basically I was
creating a string that ontained the Fourier representation of the vector
and then evaluating the resultant function.

I know this can be done simpler using loops - I jst wanted to see how I
could do this using a bit of code generation

More information about the Python-list mailing list