Skip to content

Have various classes inherit from Generic for type checking #7624

@bradykieffer

Description

@bradykieffer

Checklist

  • I have verified that that issue exists against the master branch of Django REST framework.
  • I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
  • This is not a usage question. (Those should be directed to the discussion group instead.)
  • This cannot be dealt with as a third party library. (We prefer new functionality to be in the form of third party libraries where possible.)
  • I have reduced the issue to the simplest possible case.
  • I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)

Steps to reproduce

Internally we've been using djangorestframework-stubs(link here) and it's been really great at helping us avoid some weird classes of errors. My proposal would be to have the following classes inherit from Generic as they do within djangorestframework-stubs:

  • ClassLookupDict
  • DataAndFiles
  • BaseSerializer
  • Field
  • RelatedField

This is definitely related to #7385 which added __class_getitem__ to the BaseSerializer class.

Pros

  • No longer need to add the somewhat boilerplate-y __class_getitem__ to any generic class
  • A class marked as Generic[KeyType, ValueType] will raise an exception if not typed with two typed parameters
  • It's in the standard library, I would argue it's the more idiomatic approach to typing
  • Generic was introduced in Python 3.5, which is the oldest supported version of Python with DRF
  • There are various checks within the internals of Generic to ensure that type annotations are indeed valid types

Cons

  • Muddling typed code with untyped code - bitrot could occur because mypy checks aren't enforced on DRF
  • Python versions pre-3.7 used a different metaclass for Generic, so we'd need special handling for as long as Python 3.5 and 3.6 are supported by the project
  • There's some potentially un-intuitive behavior with MyClass[int] not being the same as MyClass (which definitely feels correct) and it breaks current functionality

I have a patch that I'll link to this ticket, I don't think there's really a burden on implementation here 😄

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions