Unsoundness with `typing.IO` and friends
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 1.8k
- Fork
- 302
- Merge medio
- 23h
- PR unite (30g)
- 8
Descrizione
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 .)
Guida per i contributori
Nessuna guida per i contributori indicizzata per questo repository
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia esaminando il comportamento a runtime di typing.IO, typing.BinaryIO, typing.TextIO e io.BytesIO, insieme alle loro relazioni in typeshed e alla issue di CPython collegata. Confronta i tre approcci proposti e documenta o implementa una specifica e una direzione di runtime concordate; per considerare il lavoro completato, è necessario risolvere come devono comportarsi isinstance() e issubclass().
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- tooling
- Tipo di issue
- Funzionalità
- Difficoltà
- 5/5
- Tempo stimato
- Più di una settimana
- Stato di attività
- Ferma
- Chiarezza
- Da chiarire
- Idoneità per principianti
- 25/100