python / python/typing

Add safer types of casts

未关闭
#565 6 条评论 1 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

topic: feature
主要语言
Python
星标
1.8k
派生
302
平均合并
23 小时
30 天内合并 PR
8

描述

The only form of cast expression we have is intended to completely bypass the type system. This is like most forms of casting in C (not counting conversions) -- it never fails either at runtime or at compile time.

Maybe we can add two new types of casts:

Downcast

downcast(T, E) checks at compile time that the type of expression E is a supertype of T, and checks at runtime that E is in fact an instance of T. As a special case, if the type of E is Any, the compile time check always succeeds, but the runtime check is still performed.

A possible implementation:

def downcast(type, expr):
    assert isinstance(expr, type)
    return expr

It's intentional that this uses assert (though debatable): the intended use case is currently handled by inserting the same assert manually. IOW:

x = downcast(type, expr)

is roughly equivalent to:

assert isinstance(expr, type)
x = expr
Upcast

Probably much less needed, but proposed for symmetry and because occasionally it's useful. upcast(T, E) should check at compile time that T is a supertype of the type of E, and at runtime it's a no-op.

A possible implementation:

def upcast(type, expr):
    return expr

This fragment:

x = upcast(type, expr)

is roughly equivalent to:

x: type = expr

except that it works even if the type of x has already been declared.

贡献指南

这个仓库没有索引到贡献指南

从这里开始

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

调研方向

首先查看 issue 正文中提出的 downcast 和 upcast 语义。文中没有指定文件、测试或入口点;第一步是确定一套达成共识的设计,之后才需要进行实现和测试。

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

评估

技术栈
python
领域
tooling
Issue 类型
功能
难度
5/5
预计耗时
一周以上
活跃度
停滞
描述清晰度
需要澄清
新手友好度
30/100

把新 issue 发到你的邮箱

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