Make each assignment to define a distinct variable with independent type

未关闭
#18,516 4 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

评估

难度
5/5
预计耗时
一周以上
新手友好度
25/100
Issue 类型
功能
描述清晰度
基本清楚
活跃度
停滞
技术栈
python
领域
compilers

调研方向

首先阅读相关 issue #6233 和 #6232,然后查看 issue 中提到的原型实现。拟议的工作是使用不同的内部变量和 phi 节点进行通用变量重命名遍历,并以兼容当前语义为完成目标。

由索引模型根据 Issue 内容生成。

描述

feature priority-0-high

These long-standing issues can be solved by generalizing the variable renaming pass that is used by --allow-redefinition:

  • #6233
  • #6232

Each assignment to a name would generate a separate internal variable. We will use "phi nodes" to merge these variables when different control flow paths assign to different variants. Here is a simple example:

def f() -> None:
    if c():
        x = 0
    else:
        x = ""
    reveal_type(x)

The new variable renaming pass would produce a new AST that resembles this program (note that phi(...) is a new special AST node type and not a function call):

def f() -> None:
    if c():
        x = 0
    else:
        x' = ""
    x'' = phi(x, x')
    reveal_type(x'')  # int | str

This resembles the static single assignment form (SSA) used by many compilers, but probably would not conform to it 100% due to various practical reasons.

I'm working on a prototype implementation.

I hope that we can make this sufficiently compatible with the current semantics so that we can enable it by default (in mypy 2.0, possibly).

An alternative way to provide similar functionality would be to infer variable types from multiple assignments, similar to what already happens if a variable is declared as x: object. The renaming approach has a few notable benefits:

  • It can (more) easily support partial types (e.g. inferring a list item type from an x.append call).
  • It's a generalization of how we've already implemented --allow-redefinition.
  • It should make it easier to generate efficient code in mypyc.
  • The implementation will mostly be a new renaming pass, so it won't make other parts of mypy much more complicated (though mypyc needs changes).
  • The conditional type binder has some tech debt and I'm not excited about making it even more complicated, which would be the case if we'd use the alternative approach.
主要语言
Python
星标
20.6k
派生
3.3k
平均合并
1 天 18 小时
30 天内合并 PR
54

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

python/mypy 的其他 Issue

查看 python/mypy 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。