Re: how can I execute a function string
From: Hans Nowak (hans_at_zephyrfalcon.org)
Date: 01/13/04
- Next message: Ticachua: "Re: How to intercept a keypress using python?"
- Previous message: David M. Cooke: "Re: building strings with variable input"
- In reply to: Rajarshi Guha: "how can I execute a function string"
- Next in thread: Francis Avila: "Re: how can I execute a function string"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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/
- Next message: Ticachua: "Re: How to intercept a keypress using python?"
- Previous message: David M. Cooke: "Re: building strings with variable input"
- In reply to: Rajarshi Guha: "how can I execute a function string"
- Next in thread: Francis Avila: "Re: how can I execute a function string"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|