Hello when I try the next code with sympy I can not cath the exeption of SyntaxError
from sympy.abc import x, y
try:
e =x + y + x)
# except Sympifyerror
except exception:
# except SyntaxError as error:
# except SyntaxError as ex:
raise SyntaxError('Error during evaluation of sympy expression: '
+ str(ex))
print ("errores")
Thanks
You cannot catch
SyntaxError, since it is raised prior code execution (i.e. before try and except are executed); If you use
eval
, you can be able to catch it, e.g.
from sympy.abc import x, y
code = """
e = x + y + x)
"""
try:
eval(code)
except SyntaxError:
print("Hello")
But when I try I get:
Error:
psm@psm:~/Documentos$ python scriptsympy.py
Traceback (most recent call last):
File "scriptsympy.py", line 18, in <module>
main()
File "scriptsympy.py", line 8, in main
eval(e =x + y + x)
TypeError: eval() takes no keyword arguments
what's that mean?
eval() cannot evaluate a statement with an equal sign in it. The interpreter is understanding "e = ..." as assigning the keyword argument "e" to the value of "x + y + x".
from sympy.abc import x, y
code = """
x + y + x
"""
try:
e = eval(code)
except SyntaxError:
print("Hello")
Hello again, new problems, when I run my code:
#!/usr/bin/python3.6
def main():
from sympy.abc import x, y
code = """
x + y + x
"""
try:
e=eval(code)
except SyntaxError:
print ("errores")
print (e)
if __name__ == "__main__":
main()
I've found the following mistake:
Error:
UnboundLocalError: local variable 'e' referenced before assignment
What I'm doing wrong?
Thanks
Ok, exec
would be more appropriate in this case.
As far as I understand, we want to raise SyntaxError intentionally, so why I left extra closing parenthesis.
So, variable assignment e =...
or extra )
both causes SyntaxError, that is good.
But what about the error message:
UnboundLocalError
Since your code snippet is unformatted, I can just suppose what exactly code you ran.
def main():
from sympy.abc import x, y
code = """
x + y + x
"""
try:
e = eval(code)
except SyntaxError:
print ("errores")
print(e)
if __name__ == "__main__":
main()
Error:
UnboundLocalError: local variable 'e' referenced before assignment
This is because the expression to be evaluated (the
code
string) includes spaces that causes
IndentationError
.
IndentationError
, in turn, is subclass of
SyntaxError
, so,
print(errors)
is executed and variable
e
is not being assigned. This is why
UnboundLocalError
raised.
Hello, I take out the sapaces:
def main():
from sympy.abc import x, y
code = """
x+y+x
"""
try:
e=eval(code)
except SyntaxError:
print ("errores")
print (e)
if __name__ == "__main__":
main()
And I have the same problem, how can I resolve my problem?
Error:
UnboundLocalError: local variable 'e' referenced before assignment
def main():
from sympy.abc import x, y
code = """x+y+x"""
e = None
try:
e = eval(code)
except SyntaxError:
print ("errores")
if e is not None:
print(e)
if __name__ == "__main__":
main()