django-stubs icon indicating copy to clipboard operation
django-stubs copied to clipboard

Type error when using async function based view in url path function

Open medihack opened this issue 1 year ago • 1 comments

Bug report

What's wrong

When using the below snippet ...

from django.http import HttpResponse
from django.urls import path


def sync_view() -> HttpResponse:
    return HttpResponse(status=200)

async def async_view(): 
    return HttpResponse(status=200)

urlpatterns = [
    path("foo/", sync_view),
    path("bar/", async_view)  # <-- type error
]

... I got the below type error when calling path with the async view:

No overloads for "path" match the provided arguments Pyright[reportGeneralTypeIssues](https://github.com/microsoft/pyright/blob/main/docs/configuration.md#reportGeneralTypeIssues)
conf.pyi(26, 5): Overload 3 is the closest match
Argument of type "() -> Coroutine[Any, Any, HttpResponse]" cannot be assigned to parameter "view" of type "Sequence[URLResolver | str]" in function "path"
  "function" is incompatible with "Sequence[URLResolver | str]"Pyright[reportGeneralTypeIssues](https://github.com/microsoft/pyright/blob/main/docs/configuration.md#reportGeneralTypeIssues)
def async_view()
Full name: adit.dicom_explorer.urls.async_view
(function) def async_view() -> Coroutine[Any, Any, HttpResponse]

I used the latest pyright version (not tested with mypy).

How it should be

path function should accept an async function based view.

System information

  • OS:
  • python version: 3.11
  • django version: 4.27
  • pyright version: 1.1.339
  • django-stubs version: 4.2.7
  • django-stubs-ext version: 4.2.7

medihack avatar Dec 13 '23 00:12 medihack

Just to complete things ... I also tested this with mypy v1.7.1, and it also gives me a type error there:

Argument 2 to "path" has incompatible type "Callable[[], Coroutine[Any, Any, HttpResponseBase]]"; expected "Callable[..., HttpResponseBase]" [arg-type]

As a side note, django-types (from which I tried to switch) does not seem to have this problem.

medihack avatar Dec 13 '23 17:12 medihack

i'm also encountering this issue as well -- is there any update on this?

bmrobin avatar Apr 10 '24 21:04 bmrobin

Same problem Seems like you should be able to solve with something like:

# path()
@overload
def path(
    route: _StrOrPromise, view: Callable[..., Coroutine[Any, Any, HttpResponseBase]], kwargs: dict[str, Any] = ..., name: str = ...
) -> URLPattern: ...

# re_path()
@overload
def re_path(
    route: _StrOrPromise, view: Callable[..., Coroutine[Any, Any, HttpResponseBase]], kwargs: dict[str, Any] = ..., name: str = ...
) -> URLPattern: ...

jlost avatar Apr 25 '24 13:04 jlost

Closed via #2085

flaeppe avatar Apr 27 '24 08:04 flaeppe