python / python/typing

Unsoundness with `typing.IO` and friends

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

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

topic: other
主要言語
Python
スター
1.8k
フォーク
302
平均マージ
23時間
マージ済み PR(30日)
8

説明

The classes typing.IO, typing.BinaryIO, and typing.TextIO look like they want to be Protocols or ABCs, but in fact they are defined as regular generic classes, both at runtime and in typeshed. However, they are meant to encompass the concrete IO classes defined in the io module, and in typeshed we implement that by having these classes inherit from typing.*IO classes, even though there is no such inheritance at runtime.

This can easily lead to unsound behavior:

import io, typing

def f(x: int | io.BytesIO) -> int:
    if isinstance(x, typing.BinaryIO):
        return x.fileno()
    return x

f(io.BytesIO()) + 1  # boom

Type checkers think BytesIO is a subclass of BinaryIO, because that's how it's defined in typeshed, but in fact it isn't at runtime.

I can see a few solutions:

  1. Special-case typing.*IO in the spec and say that type checkers should reject isinstance()/issubclass() calls involving them.
  2. Deprecate the typing.*IO classes and eventually remove them, nudging people to use their own Protocols (or the new io.Reader/io.Writer) instead. This is conceptually clean but may be annoying for a lot of users; the typing classes are nice to use in simple application code.
  3. Make these classes actually (runtime-checkable?) Protocols at runtime, though they would be unwieldily large.

Even if we do (2) or (3) type checkers might still want to do (1) since it will be a while before the relevant runtime changes take effect.

(Noticed this while looking into https://github.com/python/cpython/issues/133492 .)

コントリビューションガイド

このリポジトリのコントリビューションガイドは索引されていません

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

調査の方向性

まず、typing.IO、typing.BinaryIO、typing.TextIO、io.BytesIO の実行時の動作、それらと typeshed の関係、およびリンクされている CPython issue を確認します。提案されている 3 つのアプローチを比較し、合意した仕様と実行時の方向性を文書化または実装します。完了とするには、isinstance() と issubclass() がどのように動作すべきかを解決する必要があります。

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

評価

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

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

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