asgiref
asgiref copied to clipboard
Preserving typing on `async_to_sync`/`sync_to_async` wrapped functions
Currently wrapping functions with these class based decorators will obliterate type information. With the introduction of Paramspec
in python 3.10 and the backports library typing_extensions
it should be possible (using Generic
) to preserve this information.
The code for this looks like this
from typing_extensions import ParamSpec
from typing import Callable, Generic, TypeVar
return_value = TypeVar("return_value")
parameters = ParamSpec("parameters")
class FooDecorator(Generic[parameters, return_value]):
def __init__(self,func: Callable[parameters, return_value]):
self.func = func
def __call__(self,*args:parameters.args, **kwargs:parameters.kwargs)-> return_value:
return self.func(*args,**kwargs)
This would currently be blocked by a bug in the typing backport (https://github.com/python/typing/pull/817), but is soon to resolved. I would be happy to create a PR for this once the bug is resolved.
Yes, let's get this in once it's possible with the backport. The decorators have always been very annoying when typing is involved!
The blocking MR has now been released as part of the 3.10 version of typing extensions. Any blockers to me having a go at implementing this?
I don't think so, I'd love someone else to take on mypy stuff rather than having to stare at it for hours!
mypy 0.920 is out now
Not realising there was an existing older PR in #298 that I could've based off, I've added a new PR that addresses this in #373...however, it appears we took mostly the same approach.
Done plenty of typing on private projects, but this is a first for an open source project, so feedback would be appreciated.
Also worth noting and discussing; the minimum mypy version for this PR to work is 0.991. Given mypy 1.0.0+ is out now, I'm not sure how much of an issue this is anymore, but it still might be deserving of some consideration as to whether it will cause people issues if they are forced to upgrade their mypy version. At the least, it probably means this should only be added in a minor asgiref release (eg 3.7.0) ?
This got resolved in #390