Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python type hinting on imported modules

I find that the autocomplete for Flask is somewhat lacking. This is because internally, context-specific objects such as current_app, request, and logger are actually LocalProxy objects. Thus PyCharm reasonably has no idea what to do with this type.

One solution would be to apply type hints to the imported modules. Except you can't do that! As of Python 3.7 there appears to be no such syntax to facilitate this.

So the next-obvious solution would be to make local copies of each context-specific module with the type explicitly set like so:

from logging import Logger
from flask import Flask, Request, Blueprint, request, current_app as app
    
app: Flask = app
logger: Logger = app.logger
request: Request = request

This works until you actually attempt to start the server, in which case the application crashes because of a RuntimeError: Working outside of application context.

It turns out that we can actually encapsulate the relevant type hints inside of a class or other scope inside of the application context.

@foo_blueprint.route('/foo', methods=['GET'])
def foo(cls):
    _app: Flask = app
    _logger: Logger = app.logger
    _request: Request = request
    # ...

This works but is incredibly awkward in every imaginable sense.

Is there a reasonable solution for getting proper type hints inside of an application context in Flask?

like image 550
I'll Eat My Hat Avatar asked Nov 09 '18 08:11

I'll Eat My Hat


People also ask

Should you use Python type hints?

In his excellent article The State of Type Hints in Python, Bernát Gábor recommends that “type hints should be used whenever unit tests are worth writing.” Indeed, type hints play a similar role as tests in your code: they help you as a developer write better code.

Are type hints enforced in Python?

Type hints are performed using Python annotations (introduced since PEP 3107). They are used to add types to variables, parameters, function arguments as well as their return values, class attributes, and methods. Adding type hints has no runtime effect: these are only hints and are not enforced on their own.

How do you type hinting in Python?

Here's how you can add type hints to our function: Add a colon and a data type after each function parameter. Add an arrow ( -> ) and a data type after the function to specify the return data type.

Does Python make hinting faster?

There's no effect on performance whatsoever with or without type hints. Cpython ignore type hints similar to how comments are discarded during runtime.


1 Answers

Update 2022

Starting in Flask version 2.0.0, type hints are now built-in to the library. (See pull request #3973)

Version of Flask prior to 2.0.0

For older version of Flask, one workaround is to use a type cast as follows:

from typing import cast

from flask import request
from flask import Request
from flask import Response


@app.route('/')
def index() -> Response:
    # Can't use `assert isinstance(request, Request)`, since `request` is `LocalProxy` object.
    global request
    request = cast(Request, request)

    token = request.headers.get('authorization')
    ... 
    return 'API is working', 200
like image 84
Christopher Peisert Avatar answered Nov 13 '22 16:11

Christopher Peisert