asgiref icon indicating copy to clipboard operation
asgiref copied to clipboard

Preserving typing on `async_to_sync`/`sync_to_async` wrapped functions

Open shughes-uk opened this issue 3 years ago • 7 comments

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.

shughes-uk avatar Jun 14 '21 06:06 shughes-uk

Yes, let's get this in once it's possible with the backport. The decorators have always been very annoying when typing is involved!

andrewgodwin avatar Jun 14 '21 15:06 andrewgodwin

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?

shughes-uk avatar Sep 25 '21 16:09 shughes-uk

I don't think so, I'd love someone else to take on mypy stuff rather than having to stare at it for hours!

andrewgodwin avatar Sep 26 '21 16:09 andrewgodwin

mypy 0.920 is out now

graingert avatar Dec 16 '21 22:12 graingert

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.

LucidDan avatar Feb 19 '23 01:02 LucidDan

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) ?

LucidDan avatar Feb 19 '23 01:02 LucidDan

This got resolved in #390

LucidDan avatar Jun 02 '23 09:06 LucidDan