pythondjangopython-typing

How to annotate Django view's methods?


I'd like to use Python type hints in my Django project. What's the proper way to annotate get/post methods of a simple class-based view in Django?

I've searched the Django code itself but it doesn't seem to contain any type hints.


Solution

  • [UPDATE 15/12/2022]: Well I have forgotten this answer, but it seems that you don't need a project that is not maintained for the last 6 years if you use Python 3.6+.

    Just use typing (if needed) and type hints as normal.

    Example:

    def get(self, request: HttpRequest, question_id: typing.Optional[str] = None) -> HttpResponse:
        # code here
    

    There exists this repository which may interest you: https://github.com/machinalis/mypy-django
    which will allow you to use annotations like so:

    def get(self, request: HttpRequest, question_id: str) -> HttpResponse: