Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

GenericAPIView has missing type parameters, but when added 'type' object is not subscriptable #255

Closed
XF-FW opened this issue Sep 21, 2022 · 5 comments
Labels
bug Something isn't working

Comments

@XF-FW
Copy link
Contributor

XF-FW commented Sep 21, 2022

Bug report

What's wrong

When using mypy with strict=true, it issues the following error:
Missing type parameters for generic type "GenericAPIView".

So, I check the type and add it, but I'm now getting a runtime error:
TypeError: 'type' object is not subscriptable.

I am using django_stubs_ext.monkeypatch(), which solves the problem for other similar issues.

I haven't test it on its own, but this should suffice, as a reproducible test:

from rest_framework.generics import GenericAPIView

class ShouldWorkView(GenericAPIView[None]):
   ...

How is that should be

The above example should pass, with no issues.

System information

  • OS: Arch
  • python version: 3.10
  • django version: 4.0.7
  • mypy version: 0.942
  • django-stubs version: 1.12.0
@XF-FW XF-FW added the bug Something isn't working label Sep 21, 2022
@ewiner
Copy link

ewiner commented Sep 22, 2022

I believe you're hitting this issue: https://mypy.readthedocs.io/en/latest/runtime_troubles.html#using-classes-that-are-generic-in-stubs-but-not-at-runtime. The solution suggested on that doc page worked for me.

@XF-FW
Copy link
Contributor Author

XF-FW commented Sep 22, 2022

Yep, that worked. Thanks!

It still feels like a workaround, so I'll leave this open. If the maintainers feel like this should be the default behavior, feel free to close it.

@XF-FW
Copy link
Contributor Author

XF-FW commented Nov 5, 2022

The same thing happens when trying to subclass PrimaryKeyRelatedField.

Edit: And Field.

@monosans
Copy link

monosans commented Nov 18, 2022

You can pass the classes you want to monkeypatch in the extra_classes parameter to django_stubs_ext.monkeypatch().

Example:

import django_stubs_ext
from rest_framework import fields, generics

django_stubs_ext.monkeypatch(
    extra_classes=(fields.Field, generics.GenericAPIView)
)

or you can manually monkeypatch them:

from rest_framework import fields, generics

for cls in (fields.Field, generics.GenericAPIView):
    cls.__class_getitem__ = classmethod(  # type: ignore[attr-defined]
        lambda cls, *args, **kwargs: cls
    )

@XF-FW
Copy link
Contributor Author

XF-FW commented Nov 18, 2022

Thank you! That works perfectly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Development

No branches or pull requests

3 participants