-
Notifications
You must be signed in to change notification settings - Fork 242
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Annotate sync/async code via Generic | generic TypeVar / Type aliases in Generic #1183
Comments
Might be duplicate / use case of #548 |
Perhaps something like this? import asyncio
from typing import Any, Coroutine, Generic, TypeVar, overload
from httpx import AsyncClient, Client, Response
ClientT = TypeVar("ClientT", bound=Client | AsyncClient)
class API(Generic[ClientT]):
def __init__(self, client: ClientT) -> None:
self.client = client
@overload
def get_items(self: "API[Client]") -> Response: ...
@overload
def get_items(self: "API[AsyncClient]") -> Coroutine[Any, Any, Response]: ...
def get_items(self) -> Response | Coroutine[Any, Any, Response]:
return self.client.request('get', 'https://example.com/api/v1/get_items') |
Interesting. It could work, I'll try it. Thank you! Though, does it imply that every method needs to be annotated as like thus, or it can be done only for root methods and return annotations for ones that use them can be omitted? |
This would have to be done for every method that becomes |
Then I'd say its too much of a duplication/overloads that going to obstruct actual code. Writing it in .pyi files will help with readability, but still will make process of writing/changing the code more complicated than it should be. |
There really isn't a way to correctly type this without overloads. The solution suggested at the end of the question wouldn't really work, even if HKTs did make it into Python, as it would allow for something like response = await API[Client, Awaitable](Client()).get_items() without the type checker complaining. This is equivalent to having a P.S.: I would also switch |
Consider this case:
How can I express bound between
ClientT
and return type ofAPI().get_items()
?How it could look like if
Generic
would support type aliases or TypeVar supported another type variables:Sorry if it's the wrong place/type for this issue.
The text was updated successfully, but these errors were encountered: