How to fix the syntax of a function which is in string format?
Question:
I have a text file containing python functions in string format. My code reads each function from the text file, feeds it with the appropriate inputs and then runs it. To run a function string (for example fun_str
) from the text file, I use the following snippet in my code:
dict = {}
exec(fun_str, globals(), dict)
f, = dict.values()
f()
As long as each function string has the python standard syntax (in terms of indentations, new lines, etc), the code works well. However, if the code reads a function string such as:
"def fun(list): output_list = [] for i in list: if i not in output_list: output_list.append(i) return output_list"
(all in one line)
then SyntaxError: invalid syntax
is raised with ^^^
under for
.
Is there any built-in module or any approach to fix the function string so that it follows the standard syntax before it is run by exec
?
Answers:
If you take some python code and remove all newlines, it is not necessaraily possible to convert back to the original.
For example:
def f(x): if x == None: return doSomething(x)
could mean either:
def f(x):
if x == None:
return doSomething(x)
or
def f(x):
if x == None:
return
doSomething(x)
So it wouldn’t be possible unless you know something about that code that allows you to unambiguously convert it back to its original meaning.
I have a text file containing python functions in string format. My code reads each function from the text file, feeds it with the appropriate inputs and then runs it. To run a function string (for example fun_str
) from the text file, I use the following snippet in my code:
dict = {}
exec(fun_str, globals(), dict)
f, = dict.values()
f()
As long as each function string has the python standard syntax (in terms of indentations, new lines, etc), the code works well. However, if the code reads a function string such as:
"def fun(list): output_list = [] for i in list: if i not in output_list: output_list.append(i) return output_list"
(all in one line)
then SyntaxError: invalid syntax
is raised with ^^^
under for
.
Is there any built-in module or any approach to fix the function string so that it follows the standard syntax before it is run by exec
?
If you take some python code and remove all newlines, it is not necessaraily possible to convert back to the original.
For example:
def f(x): if x == None: return doSomething(x)
could mean either:
def f(x):
if x == None:
return doSomething(x)
or
def f(x):
if x == None:
return
doSomething(x)
So it wouldn’t be possible unless you know something about that code that allows you to unambiguously convert it back to its original meaning.