SymPy: Safely parsing strings

旧巷老猫 提交于 2019-12-23 10:57:24

问题


SymPy comes equipped with the nice sympify() function which can parse arbitrary strings into SymPy expressions. But it has two major drawbacks:

  1. It is not safe, as it relies on the notorious eval()
  2. It automatically simplifies the read expression. e.g. sympify('binomial(5,3)') will return the expression 10.

So my questions are:

First, is there a way to "just parse" the string, without any additional computations? I want to achieve something like this effect:

latex(parse('binomial(5,3)')) #returns '{\\binom{5}{3}}'

Second, is there an accepted way to sympify (i.e. parse and compute) arbitrary user-generated strings while remaining safe? It is done by SymPy Gamma, so it's possible in practice, but the question is how much dirty work is needed.


回答1:


Look at the internal functions in the SymPy parsing module.

There is no official way to do it. We need to rewrite sympify to avoid eval. Note that SymPy gamma just uses sympify. It remains safe because it's sandboxed on the App Engine.



来源:https://stackoverflow.com/questions/21131128/sympy-safely-parsing-strings

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!