Skip to content
This repository has been archived by the owner on Apr 4, 2024. It is now read-only.

Add Types #27

Open
hmajid2301 opened this issue Dec 27, 2021 · 1 comment
Open

Add Types #27

hmajid2301 opened this issue Dec 27, 2021 · 1 comment

Comments

@hmajid2301
Copy link

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

@dimaqq
Copy link

dimaqq commented Apr 27, 2022

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. python/mypy#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:

Or you can import `SocketManager` object that exposes most of the SocketIO functionality.
```python
# socket_handlers2.py
from .app import socket_manager as sm
@sm.on('leave')
async def handle_leave(sid, *args, **kwargs):
await sm.emit('lobby', 'User left')
```

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants