How to type result based on constructor parameters?
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 20.6k
- Fork
- 3.3k
- Metriche di merge delle PR
- Metriche PR in attesa
Descrizione
I am trying to type code like this:
class A:
def __init__(self, return_tuple=False):
self.return_tuple = return_tuple
def __call__(self):
if self.return_tuple:
return (1, 2)
return 1
I have tried to make A generic and use overloads on the self parameter in several ways but none seems to work:
class A(Generic[T]):
def __init__(self, return_tuple: T = False) -> None:
self.return_tuple = return_tuple
@overload
def __call__(self: A[Literal[True]]) -> Tuple[int, int]:
pass
@overload
def __call__(self: A[Literal[False]]) -> int
pass
def __call__(self) -> Union[int, Tuple[int, int]]:
if self.return_tuple:
return (1, 2)
return 1
where T is either
T = TypeVar("T", bool)
or
T = TypeVar("T", Literal[True], Literal[False])
The first case mark errors in the definition of the TypeVar, the Generic and the optional parameter in __init__. The second one marks an error only in the optional parameter (even if it is essentially the same type). reveal_type does not have the expected result in both cases.
Am I doing something wrong or is this case just not currently taken into consideration?
Guida per i contributori
Apri la guida per i contributori
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
Non vengono indicati file o test. Inizia con gli esempi di Generic[T], gli overload di Literal, il parametro del costruttore e reveal_type nell’issue; segui il modo in cui mypy gestisce questi pattern e determina quale comportamento è previsto. Il lavoro è completato quando si stabilisce se questo pattern di typing è supportato e si identifica la limitazione pertinente o la modifica richiesta.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- devtools
- 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