Search code examples
pythonmypysanic

Type checking variables on the sanic context object?


The sanic python http server provides a context object for global state. A nice newer feature of python is type checking, which can detect misspelled attributes. Is there a way of telling a type system like mypy what attributes, and their types you want to add to context object?


Solution

  • Because the object is a SimpleNamespace, there is no OOTB way to handle this. But, you have a few alternatives.

    First, you can use Sanic Extensions to inject an object that is typed.

    foo = Foo()
    
    app.ext.dependency(foo)
    
    @app.get("/getfoo")
    async def getfoo(request: Request, foo: Foo):
        return text(foo.bar())
    

    Second, you could create a custom object that is typed and pass that to Sanic.

    class CustomContext:
        foo: int
    
    app = Sanic(..., ctx= CustomContext())
    
    
    ctx: CustomContext = app.ctx
    

    Third, you could subclass the Sanic class and provide a typed object.