Test a Python function within Python without importing

  • Thread starter Marco Aschwanden
  • Start date
M

Marco Aschwanden

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
 
M

Marco Aschwanden

use exec on the compiled object - the details are in the docs.

I did it... but exec() does not return a value - or does it?[/QUOTE]

Oops... it sets global vars... I didn't think of that! Thanks,
Marco
 
P

Peter Hansen

Marco said:
I did it... but exec() does not return a value - or does it?

And note, though you probably discovered this already, that
exec is a statement, not a function. Don't use the parentheses,
and you won't expect a return value... (as with print, for example).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top