I am getting mypy errors I do no completely understand. I have a generic base class and want to create a (generic) base serializer which shall be used by the specific serializer.
My code looks like this:
from typing import Generic, TypeVar
from django.db.models import Model
from rest_framework import serializers
class BaseClass(Model):
class Meta:
abstract = True
@classmethod
def some_base_class_method(cls) -> None:
pass
class MyClass(BaseClass):
class Meta:
abstract = False
_M = TypeVar("_M", bound=BaseClass)
class BaseClassSerializer(serializers.ModelSerializer[_M]):
def some_method(self) -> None:
self.Meta.model.some_base_class_method()
class MyClassSerializer(BaseClassSerializer[MyClass]):
class Meta:
model = MyClass
Mypy errors:
error: "type[_MT?]" has no attribute "some_base_class_method" [attr-defined]
self.Meta.model.some_base_class_method()
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If I add BaseClassSerializer.Meta.model like this:
class BaseClassSerializer(serializers.ModelSerializer[_M]):
class Meta:
model: _M
it does not help much and I get the following errors
error: Type variable "main._M" is unbound [valid-type]
model: _M
^
error: _M? has no attribute "some_base_class_method" [attr-defined]
self.Meta.model.some_base_class_method()
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I am getting mypy errors I do no completely understand. I have a generic base class and want to create a (generic) base serializer which shall be used by the specific serializer.
My code looks like this:
Mypy errors:
If I add
BaseClassSerializer.Meta.model
like this:it does not help much and I get the following errors