Exceptions? Is it possible to catch SyntaxError event?

56 views
Skip to first unread message

Michał Pawłowski

unread,
Feb 11, 2021, 5:25:06 AM2/11/21
to sympy
Hi.

I'd like to manage situation, when the formula, which I'd like to process has syntax error.

I tryied to use try except blocks, but its doesn't work, how can I achieve it?

#!/usr/bin/python3

from sympy import *

x = Symbol('x')

try:
    val_1 = x*sin(x)**2+x*cos(x)**2*
except SyntaxError:
    print('SyntaxError')
except:
    print('OtherError')

Thanks
Mike

Michał Pawłowski

unread,
Feb 11, 2021, 5:50:35 AM2/11/21
to sympy
Ok, I've found the solution!

I need to put the formula inside of quotes. And then pass it through simplify or expand functions.
The error will have such code:
OtherError:  <class 'sympy.core.sympify.SympifyError'>

Thanks
Mike

Aaron Meurer

unread,
Feb 11, 2021, 2:25:34 PM2/11/21
to sympy
It is not recommended to pass strings to SymPy functions like this.
Support for this will eventually be removed. If you want to convert a
string to a SymPy expression, it's better to pass it to sympify()
(note the different spelling from simplify()) first, like

expr = sympify('x*sin(x)**2+x*cos(x)**2')
expand(expr)

This will raise SympifyError if there is a syntax error, as you noted.

You can also use parse_expr() if you want more low-level control over
how strings are parsed.

Aaron Meurer
> --
> You received this message because you are subscribed to the Google Groups "sympy" group.
> To unsubscribe from this group and stop receiving emails from it, send an email to sympy+un...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/sympy/5979f86f-f838-407a-8e85-174a987935e7n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages