define a new func on the fly?

David Allen s2mdalle at titan.vcu.edu
Thu Mar 1 19:40:22 EST 2001


In article <3A9EE927.8744154E at troikanetworks.com>, "Bruce Edge"
<bedge at troikanetworks.com> wrote:

> I'm trying to define a new function on the at runtime,
> 
> this fails:
> 
>>>> eval( "def global_func_name():\n\tpass" )
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ? File "<string>", line 1
>     def global_func_name():
>       ^
> SyntaxError: invalid syntax
> 
> any idea how I can do this?

Try using lambda instead for anonymous functions,
and then bind it to a variable:

>>> squaring_function = eval("lambda x: x * x")
>>> print squaring_function(5)
25

In this respect, I don't like python's required 
whitespace, because while it keeps programmers honest
when they're programming, it makes it much more of a
pain to dynamically generate a string of code and
then eval() it as opposed to, *cough*, other 
scripting languages.

-- 
David Allen
http://opop.nols.com/
----------------------------------------
Art is anything you can get away with. 
- Marshall McLuhan.



More information about the Python-list mailing list