python / python/typing

Add safer types of casts

オープン
#565 コメント 6 件 リアクション 1 件 担当者 0 名 GitHub で見る

まだ誰も着手していません。

topic: feature
主要言語
Python
スター
1.8k
フォーク
302
平均マージ
23時間
マージ済み PR(30日)
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. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まず、issue本文で提案されているdowncastとupcastのセマンティクスを確認してください。ファイル、テスト、エントリーポイントは指定されていないため、最初のステップは合意された設計を確立することです。その後、実装とテストが必要になります。

索引モデルが issue の本文から書いたものです。

評価

技術スタック
python
領域
tooling
issue の種類
機能追加
難易度
5/5
見積もり時間
1週間以上
活発さ
停滞
明瞭さ
説明が足りない
初心者へのやさしさ
30/100

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。