View definition with ->


(Alejandro Jourdan) #1

Good afternoon everyone

Studying how a django code works, I come across the following definition of a view:

def list_lists(request) -> HttpResponse:

I had never seen a view defined that way, my question is, what does the “-> HttpResponse:” at the end means?

Thanks in advance


(Vitor Freitas) #2

This is the new (optional) type annotation support on Python 3

This arrow annotation -> means that the list_lists function returns an HttpResponse object.

You can also define the expected types of parameters:

def sum(x: int, y: int) -> int:
    return x + y

This is useful especially on large code bases. You can use tools like mypy to perform a static check on your code and catch bugs that otherwise would only show up during execution time. Another benefit is that mature IDEs like PyCharm can provide very useful auto complete hints and raise flags if you are trying to pass a wrong parameter to a function.

You can read more about it here: typing — Support for type hints


(Alejandro Jourdan) #3

Thank you very much!