@classmethod
def get_serializer_class(
cls,
skip_hidden: bool = False
) -> type[serializers.Serializer]:
fields = {}
for filter_name, filter_field in cls.filters.items():
if skip_hidden and filter_field.hidden:
continue
fields[filter_name] = filter_field.serializer_field
serializer_class = type(
f'{cls.__name__}Serializer',
(cls._meta.serializer_class,),
fields)
return serializer_class
What type should I specify for the serializer_class
variable?
Now the linter shows an error: Expected type 'Type[Serializer]', got 'type' instead
I tried to specify the type Any
, but in my opinion this is the wrong solution
1
type()
function
with three arguments, return a new type object. This is essentially a dynamic form of the class statement.
The bases tuple contains the base classes.
ref
type[T]
means that the return value is expected to be a type that is a subclass of T.
You have only posted a method code, so I do not know what your meta field holds.
But to make sure that base class is the subclass of serializers.Serializer
, You can replace cls._meta.serializer_class
with serializers.Serializer
in your type
function.
@classmethod
def get_serializer_class(
cls,
skip_hidden: bool = False
) -> type[serializers.Serializer]:
fields = {}
for filter_name, filter_field in cls.filters.items():
if skip_hidden and filter_field.hidden:
continue
fields[filter_name] = filter_field.serializer_field
serializer_class = type(
f'{cls.__name__}Serializer',
(serializers.Serializer,),
fields)
return serializer_class
2