-
-
Notifications
You must be signed in to change notification settings - Fork 28
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
django-stubs
breaks type checking of DataclassSerializer.validated_data
#91
Comments
This smells a lot like a bug in either mypy or django-stubs. If you replace from __future__ import annotations
from typing import Any, Generic, TypeVar
from django.utils.functional import cached_property
import rest_framework.serializers
T = TypeVar('T')
class DataclassSerializer(rest_framework.serializers.Serializer, Generic[T]):
def __init__(self, *args: Any, **kwargs: Any):
pass
@cached_property
def validated_data(self) -> T:
pass Now, comment out the constructor, and it starts working. |
Also, if you replace this line: serializer = PersonSerializer(data={"name": "Tony", "age": 39}) with this line serializer = DataclassSerializer[Person](data={"name": "Tony", "age": 39}) it works. Until someone has evidence to the contrary, I'm going to consider this to be a bug in something else and not something that can or should be fixed in djangorestframework-dataclasses. |
@oxan Thank you for the reply. I agree this is bizarre and could very well not be a problem with this package. I reported this to |
@oxan As explained here: The underlying issue is that for type checking to work properly, To help this situation, one idea would be to add a new
This brings in Related to this, I think it would be useful in the README to show an example of how to use this library with type checkers (e.g. adding the generic type) class PersonSerializer(DataclassSerializer[Person]):
class Meta:
dataclass = Person I didn't realize that the generic types could be used until I hit a Mypy error and then jumped into the |
I'm not too fond of creating a Adding some documentation/examples about usage with mypy sounds good. It might take a while until I get around to writing that though, so feel free to open a PR with it :) |
One advantage of uses |
With this example code:
With the following Mypy configuration:
Mypy produces a false positive error:
When
django-stubs
is installed. I haven't been able to piece together why this is, but given how prevalent usage ofdjango-stubs
is for those type checking Django projects, I wanted to share this up.Environment
These combinations also trigger the error:
The text was updated successfully, but these errors were encountered: