关于“评估是邪恶的".和“同意成人"在Python中 [英] About "eval is evil" and "consenting adults" in Python

查看:76
本文介绍了关于“评估是邪恶的".和“同意成人"在Python中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到很多人在说评估是邪恶的/危险/不安全" ,因为一个人可以做以下事情:

I see many saying "eval is evil/dangerous/insecure", because one can do things like:

eval("os.system('rm -rf /')")

其他帖子中,pythoner被视为"同意成年人",您不会由于python的鸭式输入样式为鸭式,因此不必进行类型检查.

while in other posts, pythoner are considered as "consenting adults", you don't have to do type checking because of python is of style duck typing.

然后执行以下代码:

def foo(duck):
    duck.quack()

class EvilDuck(object):
    def quack(self):
        os.system('rm -rf /')

foo(EvilDuck())

您通常如何避免这种情况?pythoner何时同意成年人,什么时候不同意?

How do you usually avoid such cases? When are pythoner consenting adults, and when not?

推荐答案

eval 是邪恶的,因为用户输入有时会进入其中.您不必(也不应该)不必担心代码伪装成不删除所有文件,因为代码仍然可以做到这一点– tada:

eval is evil because user input gets into it at some point. You don’t (well, shouldn’t) have to be worried about code pretending to not delete all files, because code can do that anyways – tada:

def foo(duck):
    duck.quack()

class EvilDuck(object):
    os.system('rm -rf /')

    def quack(self):
        pass

rm -rf/也很有可能无法正常工作.;)

And rm -rf / has a good chance of not working, too. ;)

基本上,同意成年人"是信任您的密码". eval 是信任所有代码".根据获取代码的位置, eval 可能很好,但是在99%的时间中不必要,并且很难保证其安全性.

Basically, "consenting adults" is "trust your code". eval is "trust all code". Depending on where you get that code, eval can be fine, but it’s unnecessary 99% of the time, and it can also be hard to guarantee as secure.

这篇关于关于“评估是邪恶的".和“同意成人"在Python中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆