Is there a way to write a Python script that creates and executes code?
Posted
by
KaliMa
on Stack Overflow
See other posts from Stack Overflow
or by KaliMa
Published on 2012-12-10T04:27:38Z
Indexed on
2012/12/10
5:03 UTC
Read the original article
Hit count: 81
python
Is there a way in Python to create Python code inside the Python script and then execute/test it?
My function has the following type of form (as an example)
def f(n):
if n<=3: return [0, 0, 6, 12][n]
return 2*f(n-1) - 4*f(n-2) - 5*f(n-3) + 15*f(n-4)
But I want to be able to create these kinds of functions dynamically (or any arbitrary function for that matter) and then test their outputs during runtime (as opposed to copying/pasting this function into the script and then manually testing it).
Not sure if this makes sense, please ask for elaboration if needed. I've already looked into eval and exec but couldn't get them to work with entire function definitions, just basic statements like 1+2, etc.
© Stack Overflow or respective owner