本文介绍了SymPy的sympify(< string>)。evalf()有多安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道Python的 eval()是邪恶的

We know Python's eval() is evil

和整个StackOverflow中的线程建议使用SymPy的 evalf()

and threads throughout StackOverflow suggest to use SymPy's evalf().

作为Python新手,我真的不能说服自己,由于我缺乏技能, evalf()是安全的。谁能详细说明 evalf()的功能(不同)?

As a Python newbie, I can't really convince myself that evalf() is safe as I lack the skills. Can anyone elaborate on what evalf() does (different)?

推荐答案

python eval 和sympy evalf 之间没有什么共同点(后者用于计算sympy表达式树的数值并且它与解析没有任何关联,而 eval 只是与解析字符串并像对待代码一样对其进行评估)。

There is nothing common between python eval and sympy evalf (the latter is for calculating the numeric value of sympy expression trees and it has nothing to do with parsing, while eval is all about parsing a string and evaluating it as if it is code).

另一方面, sympify eval 一样危险,因为它实际上使用了 eval

On the other hand, sympify is just as dangerous as eval, because it actually uses eval.

有两种基本模式,其中 sympify 被使用,可能它们混入同一函数中可能是一个坏主意:

There are two basic modes in which sympify is used and probably it is a bad idea that they got mixed in the same function:


  • sympify(some_object)将返回更适合在CAS中使用的对象的表示形式,例如转换 int(1)放入 sympy.Integer(1)

  • sympify(some_object) would return a representation of the object more suited for use in a CAS, like transforming int(1) into sympy.Integer(1)

sympify( some_text) 会解析t他几乎直接通过 eval 发送文本(从 sympify中存在的 sympy.parsing 中搜索导入并遵循它)。由于存在一些限制,因此比较安全,但是不安全

sympify("some_text") would parse the text almost directly through eval (search for the import from sympy.parsing present in sympify and follow it). It is safer as there are some constraints but it is not safe.

这篇关于SymPy的sympify(< string>)。evalf()有多安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 04:41