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
Allow type checkers to make serializers generic #7385
Allow type checkers to make serializers generic #7385
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hi @antonagestam. I'm not that familiar with type checking, but having seen the PRs for Python/Django, this change sounds 👍 . Two questions:
- Could you add a minimal sanity check to the serializer tests?
- Would it make sense for
Serializer
s to also be generic?
cc @sobolevn
Yes, we can do the same test we did for
I guess so. We can also probably make And |
I moved Do you mind if I address |
Also, I've put the tests in the cases corresponding to the tested classes, but it might be nice to create a |
I'm having a bit of a hard time with this one. I can see that it'd ensure that say, |
@tomchristie yes, you are right!
That's only allows to write
Semantic part of this task is on us ( |
@tomchristie Static type checkers will not run this method while evaluating an annotation, they will only see The |
Okay, and type-wise what extra information does that binding then imply? Does that eg. allow the type checker to determine that |
Yes, this seems possible. We can also infer serializer fields and their types based on this information. |
The stubs decide what the type argument binds to, it won't automatically do anything. But it allows the stub implementer to give the class any number of type arguments and with any kind of meaning. If we define the stubs like this (simplified example): T = TypeVar("T", bound=Model)
class ModelSerializer(Generic[T]):
instance: T
# or even
@property
def instance(self) -> T:
...
class AuthorSerializer(ModelSerializer[Author]):
... Then mypy would infer that Here's another example where the stubs are separate from the implementation and |
Status: 🤷♂️ Yeah probably okay with it. It'd be a bit of a mysterious addition for some readers, which I'm not super excited about, but... |
Fixes #7384