PEP 482 – 类型提示文献综述
- 作者:
- Łukasz Langa <lukasz at python.org>
- 讨论列表:
- Python-Ideas 列表
- 状态:
- 最终
- 类型:
- 信息性
- 主题:
- 类型检查
- 创建:
- 2015年1月8日
- 更新历史:
摘要
本PEP是关于类型提示的三个相关PEP之一。本PEP对相关工作进行了文献综述。主要规范是PEP 484。
Python中现有的方法
mypy
(本节为占位符,因为mypy本质上是我们正在提出的内容。)
Reticulated Python
Reticulated Python由Michael Vitousek开发,是Python渐进式类型的一种略微不同的方法。它在Vitousek与Jeremy Siek和Jim Baker(后者以Jython闻名)合著的一篇学术论文中进行了描述。
PyCharm
JetBrains的PyCharm已经提供了大约四年的指定和检查类型的方法。由PyCharm建议的类型系统从简单的类类型发展到元组类型、泛型类型、函数类型等,这基于许多用户分享他们在代码中使用类型提示的经验反馈。
其他
待办事项:添加关于pyflakes、pylint、numpy、Argument Clinic、pytypedecl、numba、obiwan的部分。
其他语言中现有的方法
ActionScript
ActionScript是一种基于类的、单继承的、面向对象的ECMAScript超集。它支持接口和强运行时检查的静态类型。编译支持“严格方言”,其中类型不匹配会在编译时报告。
带有类型的示例代码
package {
import flash.events.Event;
public class BounceEvent extends Event {
public static const BOUNCE:String = "bounce";
private var _side:String = "none";
public function get side():String {
return _side;
}
public function BounceEvent(type:String, side:String){
super(type, true);
_side = side;
}
public override function clone():Event {
return new BounceEvent(type, _side);
}
}
}
Dart
Dart是一种基于类的、单继承的、面向对象的语言,具有C风格的语法。它支持接口、抽象类、具现化的泛型和可选类型。
类型在可能的情况下被推断。运行时区分两种执行模式:检查模式旨在用于开发(在运行时捕获类型错误)和生产模式建议用于快速执行(忽略类型和断言)。
带有类型的示例代码
class Point {
final num x, y;
Point(this.x, this.y);
num distanceTo(Point other) {
var dx = x - other.x;
var dy = y - other.y;
return math.sqrt(dx * dx + dy * dy);
}
}
Hack
Hack是一种与PHP无缝互操作的编程语言。它提供了可选的静态类型检查、类型别名、泛型、可空类型和lambda表达式。
带有类型的示例代码
<?hh
class MyClass {
private ?string $x = null;
public function alpha(): int {
return 1;
}
public function beta(): string {
return 'hi test';
}
}
function f(MyClass $my_inst): string {
// Will generate a hh_client error
return $my_inst->alpha();
}
TypeScript
TypeScript是JavaScript的类型化超集,它为该语言添加了接口、类、mixin和模块。
类型检查是鸭子类型。通过提供重载函数声明来指定多个有效的函数签名。函数和类可以使用泛型作为类型参数化。接口可以有可选字段。接口可以指定数组和字典类型。类可以有构造函数,这些构造函数隐式地将参数添加为字段。类可以有静态字段。类可以有私有字段。类可以有字段的getter/setter(如属性)。类型是推断的。
带有类型的示例代码
interface Drivable {
start(): void;
drive(distance: number): boolean;
getPosition(): number;
}
class Car implements Drivable {
private _isRunning: boolean;
private _distanceFromStart: number;
constructor() {
this._isRunning = false;
this._distanceFromStart = 0;
}
public start() {
this._isRunning = true;
}
public drive(distance: number): boolean {
if (this._isRunning) {
this._distanceFromStart += distance;
return true;
}
return false;
}
public getPosition(): number {
return this._distanceFromStart;
}
}
版权
本文档已进入公有领域。
来源:https://github.com/python/peps/blob/main/peps/pep-0482.rst