fastapi-socketio
fastapi-socketio copied to clipboard
Add Types
Hi,
Within VSCode I'm getting some type errors:
Cannot access member "sio" for type "FastAPI"
Member "sio" is unknown
Which makes sense because as far as VSCode knows FastAPI doesn't have an attribute sio
. Is there a way this can be fixed ? For example adding custom stub types ?
Thanks
That's going to be kinda hard when SocketManager
magically creates a .sio
on the app that's passed as an argument.
One option would be to start with app = cast(FastAPIWithSocketIO, FastAPI())
or equivalent.
The downside of that approach is only one enrichment can be used at a time -- what happens the user wants to use another fastapi-foobario
library that behaves this way?
Ideally I'd be able to declare app extensions like so: app.sio: SIO|None = None
, but alas, "Type cannot be declared in assignment to non-self attribute"
, see e.g. https://github.com/python/mypy/issues/2388
So... today, IMHO, the only solution is not to keep the sio object on the app.
After all, I think global app
singleton access is a bit of an anti-pattern (consider a larger app with many routers).
So, I would propose to have a separate sio
global instead of app.sio
app = FastAPI()
SockerManager(app)
sio = cast(socketio.asyncio_server.AsyncServer, app.sio)
Ultimately, while socket_manager
and app.sio
are different objects, the documentation claims that they can be used [mostly] interchangeably to e.g. .emit(...)
messages: https://github.com/pyropy/fastapi-socketio/blob/3dd1f3d6f63d5a0e506cbe873b3a64a68592175a/README.md?plain=1#L40-L50