Skip to content

get_serializer_context() return type should be dict, not Mapping #986

Description

@Alexerson

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions