Unsoundness with `typing.IO` and friends
維護者通常 1 天內回覆
還沒有人認領這個 Issue。
評估
研究方向
首先檢視 typing.IO、typing.BinaryIO、typing.TextIO 和 io.BytesIO 的執行期行為,以及它們與 typeshed 的關係和所連結的 CPython issue。比較提出的三種方法,並記錄或實作一份已達成共識的規格和執行期方向;完成的要求是解決 isinstance() 和 issubclass() 應如何運作。
由索引模型根據 Issue 內容生成。
描述
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:
- Special-case
typing.*IOin the spec and say that type checkers should rejectisinstance()/issubclass()calls involving them. - Deprecate the
typing.*IOclasses and eventually remove them, nudging people to use their own Protocols (or the newio.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. - 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 .)
- 主要語言
- Python
- 星號
- 1.8k
- 分支
- 302
- 平均合併
- 4 小時 16 分鐘
- 30 天內合併 PR
- 7
環境準備
我們還沒有檢查這個專案的環境設定檔。先看它的 README,通用步驟見我們的新手貢獻指南。
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
python/typing 的其他 Issue
-
topic: typing spec
難度 2/5 1-3 小時 新手友好度 72/100
python/typing#2356 · 2 則留言 · 1 個 reaction ·
維護者通常 1 天內回覆
-
topic: typing spec
難度 2/5 1-3 小時 新手友好度 75/100
維護者通常 1 天內回覆
-
topic: documentation
難度 2/5 1-3 小時 新手友好度 76/100
維護者通常 1 天內回覆
-
topic: documentation
難度 2/5 1-3 小時 新手友好度 65/100
python/typing#2150 · 2 則留言 · 2 個 reaction ·
維護者通常 1 天內回覆
-
topic: conformance tests topic: typing spec
難度 3/5 1-2 天 新手友好度 72/100
維護者通常 1 天內回覆
相似的 Issue
-
ACK_WAITING HELP_WANTED UPDATE_CS
難度 2/5 1-3 小時 新手友好度 78/100
OWASP/CheatSheetSeries#2458 ·
維護者通常 1 天內回覆
-
難度 2/5 1-3 小時 新手友好度 82/100
維護者通常 1 天內回覆
-
難度 2/5 1-3 小時 新手友好度 90/100
BasedHardware/omi#19711 ·
維護者通常 1 天內回覆
-
Qwen3_5MoeModel no longer returns router_logits, breaking aux loss with output_router_logits=True未關閉
難度 2/5 1-3 小時 新手友好度 78/100
huggingface/transformers#49172 ·
維護者通常 1 天內回覆
-
難度 2/5 1-3 小時 新手友好度 82/100
vllm-project/vllm-metal#885 ·
維護者通常 1 天內回覆