Bug report
What's wrong
GenericAPIView.get_serializer_context() is typed as returning Mapping[str, Any], which causes a type error when subclasses follow the common Django REST Framework pattern of calling super() and then adding keys to the returned context:
def get_serializer_context(self):
context = super().get_serializer_context()
context['new_key'] = True # Error here
return context
mypy reports:
Unsupported target for indexed assignment ("Mapping[str, Any]") [index]
Mapping is read-only by design, so typed assignment to its keys is not allowed. Since get_serializer_context() implementations actually return a plain mutable dict, the return type should reflect that.
How is that should be
get_serializer_context() should be typed as returning dict[str, Any] instead of Mapping[str, Any]. This matches the actual runtime return type and allows callers to mutate the context without needing a dict() cast or cast()
call:
def get_serializer_context(self):
context = super().get_serializer_context() # dict[str, Any]
context['new_key'] = True # No error
return context
Note: accepting a Mapping type as input to serializer context= is a separate and reasonable change (see #636), but the return type of get_serializer_context() should remain dict.
System information
- OS: Linux 7.0.5
python version: 3.14.4
django version: 6.0.5
mypy version: 1.20.0
django-stubs version: 6.0.4
Bug report
What's wrong
GenericAPIView.get_serializer_context()is typed as returningMapping[str, Any], which causes a type error when subclasses follow the common Django REST Framework pattern of callingsuper()and then adding keys to the returned context:mypy reports:
Mappingis read-only by design, so typed assignment to its keys is not allowed. Sinceget_serializer_context()implementations actually return a plain mutabledict, the return type should reflect that.How is that should be
get_serializer_context()should be typed as returningdict[str, Any]instead ofMapping[str, Any]. This matches the actual runtime return type and allows callers to mutate the context without needing adict()cast orcast()call:
Note: accepting a
Mappingtype as input to serializercontext=is a separate and reasonable change (see #636), but the return type ofget_serializer_context()should remaindict.System information
pythonversion: 3.14.4djangoversion: 6.0.5mypyversion: 1.20.0django-stubsversion: 6.0.4