python - Python 类型安全吗?

标签 python types type-safety dynamic-typing memory-safety

根据Wikipedia

Computer scientists consider a language "type-safe" if it does not allow operations or conversions that violate the rules of the type system.

由于 Python 运行时检查确保满足类型系统规则,我们应该将 Python 视为一种类型安全的语言。

Jason Orendorff 和 Jim Blandy 在 Programming Rust 中提出了同样的观点:

Note that being type safe is independent of whether a language checks types at compile time or at run time: C checks at compile time, and is not type safe; Python checks at runtime, and is type safe.

静态类型检查和类型安全这两个概念是分开的。

对吗?

最佳答案

许多程序员会将静态类型检查等同于类型安全:

  • “语言 A 具有 静态 类型检查,因此它类型安全的”
  • “语言 B 具有 动态 类型检查,因此它不是类型安全的”

遗憾的是,事情没那么简单。

在现实世界中

例如,C 和 C++ 不是类型安全的,因为您可以通过 Type punning 破坏类型系统。 . 此外,C/C++ 语言规范广泛允许 undefined behaviour (UB)而不是显式处理错误,这已成为安全漏洞的来源,例如 stack smashing利用和format string attack .在类型安全的语言中,这样的利用不应该是可能的。 Java 的早期版本有一个类型错误,其 Generics证明它不是完全类型安全的。

直到今天,对于 Python、Java、C++ 等编程语言......很难证明这些语言是完全类型安全的,因为它需要数学证明。这些语言大量,并且编译器/解释器存在不断出现的错误reported并得到修复。

[ Wikipedia ] Many languages, on the other hand, are too big for human-generated type safety proofs, as they often require checking thousands of cases. .... certain errors may occur at run-time due to bugs in the implementation, or in linked libraries written in other languages; such errors could render a given implementation type unsafe in certain circumstances.

在学术界

类型安全和类型系统虽然适用于现实世界的编程,但其根源和定义来自 academia ——因此,对“类型安全”究竟是什么的正式定义很困难——尤其是在谈论现实世界中使用的真实编程语言时。学术界喜欢在数学上(正式)定义称为 toy languages 的小型编程语言。 .只有这些语言才能正式证明它们是类型安全的(并证明它们的操作在逻辑上是 correct)。

[ Wikipedia ] Type safety is usually a requirement for any toy language proposed in academic programming language research

例如,学者们努力证明 Java 是类型安全的,因此他们创建了一个名为 Featherweight Java 的较小版本,并在 paper 中得到了证明。它类型安全的。同样,这个 Ph.D. paper Christopher Lyon Anderson 采用了 Javascript 的一个子集,将其称为 JS0,并证明它是类型安全的。

实际上,人们认为像 python、java、c++ 这样的适当语言不是完全类型安全的,因为它们太大了。一个小错误很容易从破坏类型系统的裂缝中溜走。

总结

  • python可能不是完全类型安全的——没有人证明这一点,这太难证明了。您更有可能在语言中发现一个小错误,证明它不是类型安全的。
  • 事实上,大多数编程语言可能不是完全类型安全 - 出于相同的原因(只有玩具学术语言已被证明是)
  • 您真的不应该相信静态类型语言是一定类型安全的。它们通常比动态类型语言更安全,但是肯定地说它们是完全类型安全的是错误的 因为没有证据证明这一点。

引用:http://www.pl-enthusiast.net/2014/08/05/type-safety/https://en.wikipedia.org/wiki/Type_system

关于python - Python 类型安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46388355/

相关文章:

python - 为 CouchDB 设置 Python ViewServer

image - 如何将 DynamicImage 转换为 ImageBuffer?

scala - 使用类型为编译时检查的任意约束建模

python - 在 django 中创建新用户给出的不是散列密码

python - 找到两个排序数组的交集,在某些情况下需要少于 O(m+n) 次比较

python - Python 属性函数的 C 代码?

java - Hibernate 查询结果列表和类型安全?

C# 可以给类起别名吗(不是 'using' )

excel - 自动导入到 access - 强制字段类型

oop - 没有类型转换的语言