Skip to content

Cannot type Flask view functions return types in the natural way #7218

Closed

Description

@dcrosta

Flask handles a variety of return types from view functions -- for instance, you can return a Response object, a str, or a tuple of str and int, etc. These are documented at https://github.com/python/typeshed/blob/master/third_party/2and3/flask/app.pyi#L48-L58.

If you need to return more than one type from a given view function, mypy gives you an error (as of python/typeshed#3003). Here's a small reproducing case, which also shows why we might want to do this:

from typing import Union
from flask import Flask, redirect, render_template
from werkzeug import Response

app = Flask(__name__)

@app.route("/")
def index() -> Union[Response, str]:
    if True:
        return redirect("/foo")           # is a Response
    return render_template("index.html")  # is a str

When we run mypy, we see:

$ mypy flaskapp.py
flaskapp.py:9: error: Value of type variable "_VT" of function cannot be "Callable[[], Union[Response, str]]"

I've logged this here, as opposed to in typeshed, as I think that mypy ought to be able to figure out from the ViewFunc definition that my particular view function is one of two valid values there, but apparently it can't.

Activity

  1. ilevkivskyi commented on Jul 15, 2019

    @ilevkivskyi
    Member

    Duplicate of #7187

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions