Replies: 3 comments 1 reply
-
I think ternary expressions are the only thing not presently supported by parse_expr that could be. Maybe also actual if/else. I'm not sure what other kinds of Python statements have corresponding SymPy expressions. |
Beta Was this translation helpful? Give feedback.
-
I think all these things could be added to the existing tokenizer based parse_expr fairly easily, although it is also true that having an ast post-processor would also make some of them easier to do. We can't completely replace tokenize with ast because tokenize handles some non-Python syntax, and also the ast loses some information like the full value of floats. |
Beta Was this translation helpful? Give feedback.
-
@asmeurer I didn't mean modifying the parse_expr implementation. I was more thinking about creating a parsing function like what we have to parse Mathematica, and use ast as a pre-processor: class SympyTransformer(ast.NodeTransformer):
# ... Implementation
def pycode_parser(python_code):
converted_python = ast.unparse(SympyTransformer().visit(ast.parse(python_code)))
return parse_expr(converted_python)
# Usage
my_py_expression = "x if x > 0 and y==1 else sin(x)"
my_sympy_expression = pycode_parser(my_py_expression) It's true that ast won't parse tokens like caret exponentiation. But if we use a separated function to parse Python code, it would be expected because caret exponentiation is not valid Python syntax. I don't know about the floating precision, but I think it's the same idea. And we keep the logic of parse_expr unchanged so we ensure there is no regression. What do you think ? |
Beta Was this translation helpful? Give feedback.
-
Hi,
I've been using Sympy for a moment and I'm surprised there is no Python parser to create Sympy expressions from Python code.
This is more or less supported for simple operations (basic arithmetics, most functions) but some syntaxes are not supported. For instance, we can't use conditions in
parse_expr()
:parse_expr("x if x > 0 and y==1 else 0")
does not provide the expected result without even throwing / raising a warning.I think such a parser is pretty doable using
ast
and converting the built-in Python syntaxes that are not supported by Sympy to some that are (a if cond else b
would becomePiecewise((a, cond), (b, True))
and we could convert the boolean arithmetics and comparisons to their corresponding sympy classes).I would like to develop this feature and contribute to the project. What do you think about it ?
Cheers,
Beta Was this translation helpful? Give feedback.
All reactions