eval()和 exec()这类语句存在的意义是什么?

2021-11-14 16:57:14 +08:00
 MiketsuSmasher
4937 次点击
所在节点    程序员
27 条回复
VtoExtension
2021-11-15 11:23:37 +08:00
脚本语言大都有这个共性,调试会方便。但是在生产环境 eval=evil
fgwmlhdkkkw
2021-11-15 15:14:42 +08:00
Python 的模板引擎都是 eval……
monetto
2021-11-15 17:24:15 +08:00
说一个稍微偏一些的吧...有的时候做装饰器的时候,有一些动态类型判断,PyCharm 可能会抽风,直接调试运行会提示类型检查不通过。这时候把条件判断表达式换成 eval 的就可以欺骗过 PyCharm 。
vkingsea
2021-11-16 11:07:27 +08:00
给你举个具体例子,
比如你使用 protobuf ,传递一个具体的消息名,现在需要用这个名字构造一个对应的消息体:

func = eval("Hello_pb2.LoginRequest")
request = func()
request.serverId = 0
request.token = "i am vkingsea"
send(request)
aguesuka
2021-11-16 13:08:19 +08:00
@monetto alt + enter suppress warring for statement. 这样相当于掩耳盗铃
monetto
2021-11-16 16:06:01 +08:00
@aguesuka 总不能要求所有人都这样来一遍吧...
aguesuka
2021-11-16 19:36:52 +08:00
@monetto
虽然手边没有 pycharme, 但是我猜它的 suppress warning type hint 是这样实现的
https://www.python.org/dev/peps/pep-0484

Compatibility with other uses of function annotations
A number of existing or potential use cases for function annotations exist, which are incompatible with type hinting. These may confuse a static type checker. However, since type hinting annotations have no runtime behavior (other than evaluation of the annotation expression and storing annotations in the __annotations__ attribute of the function object), this does not make the program incorrect -- it just may cause a type checker to emit spurious warnings or errors.

To mark portions of the program that should not be covered by type hinting, you can use one or more of the following:

a # type: ignore comment;
a @no_type_check decorator on a class or function;
a custom class or function decorator marked with @no_type_check_decorator.
For more details see later sections.

In order for maximal compatibility with offline type checking it may eventually be a good idea to change interfaces that rely on annotations to switch to a different mechanism, for example a decorator. In Python 3.5 there is no pressure to do this, however. See also the longer discussion under Rejected alternatives below.

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/815305

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX