Skip to content

fix: guard WebSocketClientProtocol import behind TYPE_CHECKING (fixes #1666)#1687

Open
mac-agent wants to merge 1 commit intosammchardy:masterfrom
mac-agent:fix/websockets14-deprecation
Open

fix: guard WebSocketClientProtocol import behind TYPE_CHECKING (fixes #1666)#1687
mac-agent wants to merge 1 commit intosammchardy:masterfrom
mac-agent:fix/websockets14-deprecation

Conversation

@mac-agent
Copy link
Copy Markdown

Problem

With websockets>=14, the runtime import of WebSocketClientProtocol triggers a DeprecationWarning:

DeprecationWarning: websockets.WebSocketClientProtocol is deprecated
DeprecationWarning: websockets.legacy is deprecated

This comes from binance/ws/websocket_api.py:4 where the class is imported unconditionally, but only used for type hints and a runtime isinstance check.

Fix

  • Wrap the import in TYPE_CHECKING: The class is only needed for static type hints, so moving it behind the guard removes the runtime import warning entirely.
  • Replace isinstance with hasattr: Since the class is no longer available at runtime, the check for ws.closed now uses hasattr instead.

No behavioral change — the WebSocket connection logic remains identical.

Addresses #1666.

…ammchardy#1666)

With websockets>=14, importing WebSocketClientProtocol at runtime
triggers DeprecationWarning about websockets.legacy being deprecated.

- Move the WebSocketClientProtocol import behind TYPE_CHECKING guard
  so it's only used for static type hints
- Replace isinstance check with hasattr check for the 'closed' attribute
  since the class is no longer imported at runtime

This eliminates the deprecation warning without changing behavior.
See: https://websockets.readthedocs.io/en/stable/howto/upgrade.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant