Infer type of generic class from return type of (optionally awaitable) callable passed to constructor
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've confirmed the following works in pyright and pyrefly - but not in mypy:
from dataclasses import dataclass
from typing_extensions import (
Awaitable,
Callable,
Generic,
TypeVar,
assert_type,
)
T = TypeVar("T")
@dataclass
class Agent(Generic[T]):
output_type: Callable[..., T] | Callable[..., Awaitable[T]]
async def coro() -> bool:
return True
def func() -> int:
return 1
# works
assert_type(Agent(func), Agent[int])
# mypy - error: Argument 1 to "Agent" has incompatible type "Callable[[], Coroutine[Any, Any, bool]]"; expected "Callable[..., Never] | Callable[..., Awaitable[Never]]" [arg-type]
coro_agent = Agent(coro)
# pyright, pyrefly - works
# mypy - error: Expression is of type "Agent[Any]", not "Agent[bool]"
assert_type(coro_agent, Agent[bool])
# works
assert_type(Agent[bool](coro), Agent[bool])
I want T to be inferred as the ultimate return type of the awaitable if an async function is passed rather than a regular one, but I suppose it's ambiguous which side of the union is the best match.
It would be great to see this work in mypy, but I'm also open to suggestions to do this in a less ambiguous way!
- This is related to a new PydanticAI feature, if you're curious check out https://github.com/pydantic/pydantic-ai/pull/1785#issuecomment-2905774110
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
Inizia eseguendo mypy sulla riproduzione fornita con dataclass, generic e callable, quindi segui il percorso di inferenza dei tipi per Agent(coro) rispetto a Agent(func). Confronta il tipo inferito con l’Agent[bool] previsto e considera come dovrebbe essere risolta l’unione di callable normali e awaitable; il lavoro è completato quando la riproduzione passa senza richiedere un argomento di tipo esplicito.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- compilers
- Tipo di issue
- Bug
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 35/100