I would like to test if a string is computable using the built in function "eval". I would like to make a condition in my definition. I want it to produce true if the string is computable using eval, and false if trying to "eval" the string produces and error. Any functions that would help me to do so? Thanks.
Example:
t="(8+(2-4)"
s="8+(2-4))"
eval(s) would produce 6
eval(t) would produce error
i want to be able to use these two conditions in my definition where I would be expecting either an integer or error from the eval expression
I'm assuming you want to check the syntax before making a call to eval(). You can try ast.parse, as mentioned in this other answer.
(Example as given in that answer, for easier reference):
import ast
def is_valid_python(code):
try:
ast.parse(code)
except SyntaxError:
return False
return True
>>> is_valid_python('1 // 2')
True
>>> is_valid_python('1 /// 2')
False