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

ApiView + custom mixing = cannot specify the type of request

Open sshishov opened this issue 3 years ago • 1 comments

Bug report

For mixin you cannot specify the type of request as it got incompatible with base View

What's wrong

from rest_framework import mixins
from rest_framework import viewsets
from rest_framework.request import Request

class MyMixin:
    request: Request

    def some_method_with_request_usage(self, *args, **kwargs):
        print(self.request)


class MyViewSet(MyMixin, mixins.ListModelMixin, viewsets.GenericViewSet):
    pass

The output is:

myfile.py:11: error: Definition of "request" in base class "MyMixin" is incompatible with definition in base class "View"  [misc]

Workaround

As a workaround, you can add the type of the request to the MyViewSet class itself.

class MyViewSet(MyMixin, mixins.ListModelMixin, viewsets.GenericViewSet):
    request: Request

But try to imagine that this mixin is used in 100 different places, why we should duplicate the type which should be inferred from the base classes:

  • Mixin has the type (Request)
  • ApiView has the type (Request)

P.S. no need to look deeper, inside View

How is that should be

No errors should be reported.

System information

  • OS: MacOS 12.3.1
  • python version: 3.9.13
  • django version: 3.2.13
  • mypy version: v0.960
  • django-stubs version: 1.11.0

sshishov avatar Jun 13 '22 16:06 sshishov