Test a Python function within Python without importing

Marco Aschwanden PPNTWIMBXFFC at spammotel.com
Tue Nov 2 15:38:25 CET 2004


Hi

I have a window that allows the user to write a python function (scite). 
Let's say the function always has 1 input param and 1 output value. eg.:

<code>
def modify_string(stuff_to_modify):
   modified_string = 'Modified: %s' % stuff_to_modify
   return modified_string
<code>

By compiling this code I can easily check whether the "string" is valid 
python code:

try:
   com = compile(code, '<string>','exec')
except Exception, msg:
   # Show msg to user if exeption occurred
   pass

If compilation and other checks went fine, I would like to offer the user 
a dialog that allows him to enter a value (input param) which is handed
to the function and the output value is shown (in label).

I could save the compiled function and import/reload it for each test 
cycle... well for various reasons I don't want that.

I thought of abusing eval... cause I could extend the entered python 
function as follows:

<code>
def modify_string(stuff_to_modify):
   modified_string = 'Modified: %s' % stuff_to_modify
   return modified_string

# Calling the function... eval could return the value...
modify_string('hallo')
</code>

But eval - as expected - chokes already on the def-statement.

How could easily test this function without having to import/reload it?

Hope the problem is clear...
Regards,
Marco




More information about the Python-list mailing list