python / python/typing

Allow `NotRequired[]` to be passed as a `TypeVar`

Aperta
#1,323 2 commenti 1 reazione 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

topic: feature
Lingua principale
Python
Stelle
1.8k
Fork
302
Merge medio
23h
PR unite (30g)
8

Descrizione

I just found myself wanting to do the following:

from typing import TypedDict, NotRequired, Generic, TypeVar, Union, Never

_T = TypeVar('_T')

Foo = Union['FooSub1[_T]', 'FooSub2[_T]', 'FooSub3[_T]']

class BaseFoo(TypedDict, Generic[_T]):
    bar: _T

class FooSub1(BaseFoo[_T]):
    sub1: str

class FooSub2(BaseFoo[_T]):
    sub2: str

class FooSub3(BaseFoo[_T]):
    sub3: str

def foo(foo_with_bar: Foo[int]):
    reveal_type(foo_with_bar) # Type of "foo_with_bar" is "FooSub1[int] | FooSub2[int] | FooSub3[int]"

def bar(foo_without_bar: Foo[NotRequired[Never]]): # error: "NotRequired" is not allowed in this context
    pass

Mypy and Pyright both disallow NotRequired to be passed as a TypeVar. However the only way to avoid doing that would require me to duplicate all subclass definitions, which I am not willing to do because I have more than a dozen and so much duplication would make the code less maintainable.

Guida per i contributori

Nessuna guida per i contributori indicizzata per questo repository

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia con il riproduttore nell’issue e confronta le regole attuali per NotRequired e TypeVar in mypy e Pyright, i due checker indicati nel report. Non sono stati identificati file o test; il lavoro sarebbe completo con un design concordato delle regole di tipizzazione e il comportamento corrispondente dei checker, senza duplicare le sottoclassi TypedDict.

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
Abbastanza chiara
Idoneità per principianti
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.