Annotate sync/async code via Generic | generic TypeVar / Type aliases in Generic
Nadie ha tomado este issue todavía.
- Lenguaje dominante
- Python
- Estrellas
- 1.8k
- Forks
- 302
- Merge medio
- 23 h
- PR fusionados (30 d)
- 8
Descripción
Consider this case:
import asyncio
from typing import Any, Coroutine, Generic, TypeVar
from httpx import AsyncClient, Client, Response
ClientT = TypeVar("ClientT", bound=Client | AsyncClient)
class API(Generic[ClientT]):
client: ClientT
def __init__(self, client: ClientT) -> None:
self.client = client
def get_items(self) -> Response | Coroutine[Any, Any, Response]:
return self.client.request('get', 'https://example.com/api/v1/get_items')
response = API[Client](Client()).get_items()
response.json() # Item "Coroutine[Any, Any, Response]" of "Union[Response, Coroutine[Any, Any, Response]]" has no attribute "json" [union-attr]
response_coroutine = API[AsyncClient](AsyncClient()).get_items()
asyncio.run(response_coroutine) # Argument 1 to "run" has incompatible type "Union[Response, Coroutine[Any, Any, Response]]"; expected "Awaitable[Response]" [arg-type]mypy(error)
How can I express bound between ClientT and return type of API().get_items()?
How it could look like if Generic would support type aliases or TypeVar supported another type variables:
import asyncio
from typing import Annotated, Any, Awaitable, Coroutine, Generic, TypeVar
from typing_extensions import reveal_type
from httpx import AsyncClient, Client, Response
ClientT = TypeVar("ClientT", bound=Client | AsyncClient)
T = TypeVar("T")
# Using Annotated just as generic type that returns its argument as is
Sync = Annotated[T, ...]
MightBeAwaitable = TypeVar("MightBeAwaitable", bound=Awaitable | Sync)
# or MightBeAwaitable = Awaitable | Sync
class API(Generic[ClientT, MightBeAwaitable):
client: ClientT
def __init__(self, client: ClientT) -> None:
self.client = client
def get_items(self) -> MightBeAwaitable[Response]: # TypeError: 'TypeVar' object is not subscriptable
return self.client.request('get', 'https://example.com/api/v1/get_items')
response = API[Client, Sync](Client()).get_items()
reveal_type(response) # Revealed type is "Response"
response_coroutine = API[AsyncClient, Awaitable](AsyncClient()).get_items()
reveal_type(response_coroutine) # Revealed type is "typing.Awaitable[Any]"
Sorry if it's the wrong place/type for this issue.
Guía de contribución
No hay ninguna guía de contribución indexada para este repositorio
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Línea de trabajo
Comienza con los ejemplos de Python de este issue y las construcciones de tipado que utilizan: Generic, TypeVar, alias de tipos, Annotated, Awaitable y Coroutine. Determina la relación prevista entre el tipo del cliente y el tipo de retorno de get_items(), y documenta un diseño de tipado compatible y los tipos revelados esperados.
Escrito por el modelo de indexación a partir del texto del issue.
Evaluación
- Stack tecnológico
- python
- Área
- developer-experience
- Tipo de issue
- Nueva funcionalidad
- Dificultad
- 5/5
- Tiempo estimado
- Más de una semana
- Estado de actividad
- Estancado
- Claridad
- Necesita aclaración
- Aptitud para principiantes
- 20/100