bitcart / universalasync

A library to help automate the creation of universal python libraries
MIT License
28 stars 2 forks source link

Mypy support #7

Open Guibod opened 2 weeks ago

Guibod commented 2 weeks ago

Hey,

Great job there, i’m wondering if you plan to support proper python typing ? I’m happy to provide very easily a sync interface to my library unfortunately, everything mypy related is broken in sync context.

If not, do you have any tips to override the typing ?

Guibod commented 2 weeks ago

As i’m tampering with the library i managed to create my own typed wrapper above async_to_sync_wraps. It’s rudimentary but it could help a lot of people. :)

from typing import (
    Any,
    AsyncGenerator,
    Callable,
    Coroutine,
    Generator,
    TypeVar,
    overload,
    Union,
)

import universalasync

T = TypeVar("T")

@overload
def synchronize(
    function: Callable[..., Coroutine[Any, Any, T]]
) -> Callable[..., Union[Coroutine[Any, Any, T], T]]: ...
@overload
def synchronize(
    function: Callable[..., AsyncGenerator[T, None]]
) -> Callable[..., Union[AsyncGenerator[T, None], Generator[T, None, None]]]: ...

def synchronize(
    f: Callable[..., Coroutine[Any, Any, T]],
) -> Callable[..., T]:
    return universalasync.async_to_sync_wraps(f)
Guibod commented 2 weeks ago

The problem is that later, mypy does not manage to infer the async or sync value from the call context.

There was a closed request for a way to handle the request context of the call (async or sync) in mypy but it was rejected: https://github.com/python/mypy/issues/9837

Guibod commented 2 days ago

I’d like to request a review of my matter, pretty please. Don’t give up on me. :)