[Tutor] executing a string representing python code

Cecilia Alm ebbaalm at uiuc.edu
Mon Mar 5 19:21:30 CET 2007


That's neat. When just the function call is the string, eval() seems
appropriate. (For example, if reading what function to call from a file.)

>>> def some_func(val):
    return val

>>> s = eval('some_func("that\'s also pretty cool")')
>>> s
"that's also pretty cool"

At any rate, thanks for the responses,
Cecilia



> You should be able to just do:
>
> >>> s = some_func("wasn't that cool")
>
> The whole point of the exec is that the function now exists in
> your local namespace. You can execute it as any other function.
>
> >> func_str = \
> >> '''
> >> def some_func(value):
> >> # youwould check value instance here and do something to it
> >>     print "Hello World", value
> >>     return "Done"
> >> '''
> >> exec(func_str)
>
> This creates the function
>
> >> f = locals()["some_func"]
> >> print f("wasn't that cool!")
>
> There should be no need for this trickery.
>
> HTH,
>
> --
> Alan Gauld
> Author of the Learn to Program web site
> http://www.freenetpages.co.uk/hp/alan.gauld
>
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
E. Cecilia Alm
Graduate student, Dept. of Linguistics, UIUC
Office: 2013 Beckman Institute
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070305/8f972d00/attachment.htm 


More information about the Tutor mailing list