How can I add python type annotations to the flask global context g?

前端 未结 3 1265
挽巷
挽巷 2021-01-05 06:07

I have a decorator which adds a user onto the flask global context g:

class User:
    def __init__(self, user_data) -&         


        
3条回答
  •  天涯浪人
    2021-01-05 06:35

    I had a similar issue described in Typechecking dynamically added attributes. One solution is to add the custom type hints using typing.TYPE_CHECKING:

    from typing import TYPE_CHECKING
    
    if TYPE_CHECKING:
        from flask.ctx import _AppCtxGlobals
    
        class MyGlobals(_AppCtxGlobals):
            user: 'User'
    
        g = MyGlobals()
    else:
        from flask import g
    

    Now e.g.

    reveal_type(g.user)
    

    will emit

    note: Revealed type is 'myapp.User'
    

    If the custom types should be reused in multiple modules, you can introduce a partial stub for flask. The location of the stubs is dependent on the type checker, e.g. mypy reads custom stubs from the MYPY_PATH environment variable, pyright looks for a typings directory in the project root dir etc. Example of a partial stub:

    # _typeshed/flask/__init__.pyi
    
    from typing import Any
    from flask.ctx import _AppCtxGlobals
    from models import User
    
    
    def __getattr__(name: str) -> Any: ...  # incomplete
    
    
    class MyGlobals(_AppCtxGlobals):
        user: User
        def __getattr__(self, name: str) -> Any: ...  # incomplete
    
    
    g: MyGlobals
    

提交回复
热议问题