2

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.

exhuma
  • 20,071
  • 12
  • 90
  • 123
  • Don!t have experience with type-hinting myself, but this seems to answer your question: https://stackoverflow.com/questions/40173982/how-can-i-type-hint-an-attribute-in-python-3-5. So, maybe `g.connection: Connection = get_connection()` will do the trick? – janpeterka Jul 01 '20 at 11:24
  • Unfortunately not. This is only good if you have access to the class-definition. This specific case is a bit tricky because 1) I don't have access to the class definitinon, and 2) The available attributes are dynamically added and can be different across different applications. I'm not actually sure if it is at all possible. – exhuma Jul 02 '20 at 12:05
  • Looks like a dup of https://stackoverflow.com/q/60123011/2650249 – hoefling Jul 02 '20 at 13:47
  • Indeed. Thanks for the pointer. I'll remove this question. Scratch that... I'll mark it as duplicate so others can find it too. – exhuma Jul 02 '20 at 14:00
  • No worries, happens to all of us. – hoefling Jul 02 '20 at 14:04

0 Answers0