python / python/typing

Annotate sync/async code via Generic | generic TypeVar / Type aliases in Generic

Offen
#1,183 6 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

topic: feature
Vorherrschende Sprache
Python
Sterne
1.8k
Forks
302
Ø Merge
23 Std.
Gemergte PRs (30 T.)
8

Beschreibung

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.

Beitragsleitfaden

Für dieses Repository ist kein Beitragsleitfaden indexiert

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginnen Sie mit den Python-Beispielen in diesem Issue und den von ihnen verwendeten Typing-Konstrukten: Generic, TypeVar, Typ-Aliase, Annotated, Awaitable und Coroutine. Bestimmen Sie die beabsichtigte Beziehung zwischen dem Client-Typ und dem Rückgabetyp von get_items(), und dokumentieren Sie ein unterstütztes Typing-Design sowie die erwarteten angezeigten Typen.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
developer-experience
Issue-Typ
Feature
Schwierigkeit
5/5
Geschätzter Aufwand
Über eine Woche
Aktivitätsstatus
Veraltet
Klarheit
Muss geklärt werden
Anfängerfreundlichkeit
20/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.