Re: how can I execute a function string

From: Hans Nowak (hans_at_zephyrfalcon.org)
Date: 01/13/04


Date: Mon, 12 Jan 2004 21:53:10 -0500
To: python-list@python.org

Rajarshi Guha wrote:

> 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
> this:
>
> def generate_func():
> s = """ def function(x):
> print x
> return 2
> """
> return s
>
> funcstring = generate_func()
> retval = ....
>
> That is, retval should have the value returned from the evaluation of the
> function in the string funcstring.
>
> Is this possible by means of simple function calls or does this involve
> some sort of black magic?

It's possible:

>>> def generate_func():
... s = """def f(x):
... print x
... return 2"""
... d = {}
... exec s in d
... return d['f']
...
>>>
>>> g = generate_func()
>>> g(4)
4
2
>>>

...but this way of doing it has several drawbacks. For example, exec is picky
about the strings it accepts; e.g. if you leave a trailing newline you get a
syntax error. Compare:

>>> def generate_func():
... s = """def f(x):
... print x
... return 2
... """
... d = {}
... exec s in d
... return d['f']
...
>>> g = generate_func()
Traceback (most recent call last):
   File "<input>", line 1, in ?
   File "<input>", line 7, in generate_func
   File "<string>", line 4

     ^
SyntaxError: invalid syntax

Also, if the string containing the syntax comes from an "untrusted source",
then it's a potential security hazard.

I'm not sure what you're trying to do here, but you might want to consider
generating an actual function, rather than a string to be evaluated:

>>> def generate_func():
... def f(x):
... print x
... return 2
... return f
...
>>> h = generate_func()
>>> h(5)
5
2

HTH,

-- 
Hans (hans@zephyrfalcon.org)
http://zephyrfalcon.org/


Relevant Pages

  • Re: func_code vs. string problem
    ... # we define 'print b' in three different ways: as a string, ... def execstring(): ... exec function.func_code ... strings and pass around as compiled objects, ...
    (comp.lang.python)
  • Re: how can I execute a function string
    ... > I have some code that generates a function on the fly in a string. ... exec generate_func ... A *slightly* better approach is to make a code object, using compile(). ... def gen_func: ...
    (comp.lang.python)
  • XML Update Question
    ... I am having trouble updating a row that has a string value for a bit column. ... Below I have given my table def, stored proc and sample data. ... EXEC sp_xml_preparedocument @hDoc OUTPUT, @XMLEmp ...
    (microsoft.public.sqlserver.programming)
  • Re: inconsistent behavior of >FLOAT
    ... If the string represents a valid floating-point number in the syntax ... if the string does not match the syntax given then false ... ">FLOAT enables programs to read floating-point data in legible ASCII format. ...
    (comp.lang.forth)
  • Re: Just a bit of silliness
    ... Is that the syntax and grammar resemble the stammer ... Can't guess how to copy a string. ... Is the very last} "close curly bracket" ... format strings. ...
    (comp.lang.c)