Following system colour scheme - Python 增强提案 Selected dark colour scheme - Python 增强提案 Selected light colour scheme - Python 增强提案

Python 增强提案

PEP 482 – 类型提示的文献综述

作者:
Łukasz Langa <lukasz at python.org>
讨论至:
Python-Ideas 邮件列表
状态:
最终版
类型:
信息性
主题:
类型标注
创建日期:
2015年1月8日
发布历史:


目录

摘要

本PEP是与类型提示相关的三个PEP之一。本PEP提供了相关工作的文献综述。主要规范是PEP 484

Python的现有方法

mypy

(本节为存根,因为mypy本质上就是我们所提议的。)

网状Python

Michael Vitousek 的网状Python 是 Python 渐进式类型化的一种略有不同方法的示例。它在 Vitousek 与 Jeremy Siek 和 Jim Baker(后者因 Jython 而闻名)合著的实际学术论文中有所描述。

PyCharm

JetBrains 的 PyCharm 在大约四年前就提供了指定和检查类型的方法。根据许多用户分享他们在代码中使用类型提示的经验反馈,PyCharm 建议的类型系统从简单的类类型发展到元组类型、泛型类型、函数类型等。

其他

待定:添加关于pyflakespylintnumpyArgument Clinicpytypedeclnumbaobiwan的章节。

其他语言的现有方法

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 的一个带类型超集,为语言添加了接口、类、混入和模块。

类型检查是鸭子类型的。通过提供重载函数声明来指定多个有效的函数签名。函数和类可以使用泛型作为类型参数化。接口可以有可选字段。接口可以指定数组和字典类型。类可以有构造函数,隐式将参数添加为字段。类可以有静态字段。类可以有私有字段。类可以有字段的 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

最后修改:2025-02-01 08:59:27 GMT