How can I type-hint attributes on `g` in `Flask`?

Viewed 187

In an application I am using Flask, which has a "magic" g variable which can be used as request-local storage, so for example, on each request, I store a reference to a DB connection on there. Along the lines of this:

from flask import before_request, g

def get_connection() -> Connection: ...


@before_request
def init():
    g.connection = get_connection()

In another module I can then do the following:

from flask import route, g

@route('/foo')
def foo():
    with g.connection.cursor() as cur:
        cur.execute(...)

But at that point, the type of g.connection is unknown and I get a typing error.

So far I have mostly ignored those, but it gets quite annoying with a larger code-base.

What makes things worse, I already have stubs in place for Flask which are shared across all of our applications. And the members attached to g are application centric, and it would be incorrect to add any typehints thereof to those shared stubs.

I have currently something like this in places where I care about type-safety:

from flask import route, g
from typing import cast

@route('/foo')
def foo():
    connection = cast(Connection, g.connection)
    with connection.cursor() as cur:
        cur.execute(...)

But that's both cumbersome and hard to maintain, as this needs to be duplicated everywhere and it risks giving inconsistent errors if type-hints need to be updated and some places are missed.

Is there any way I could put those type-hints on a central location? I know that connection will always be on g due to the before_request hook. But even casting it in that hook won't help as the typing info will get lost as soon as it is imported in another module.

0 Answers
Related