Skip to content

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

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

fix: guard WebSocketClientProtocol import behind TYPE_CHECKING (fixes #1666)#1687
mac-agent wants to merge 1 commit into
sammchardy: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
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR removes DeprecationWarning noise introduced by websockets>=14 by avoiding a runtime import of WebSocketClientProtocol in the WebSocket API client, while keeping connection checks functionally equivalent.

Changes:

  • Guard WebSocketClientProtocol import behind typing.TYPE_CHECKING to prevent runtime deprecation warnings.
  • Replace the runtime isinstance(..., WebSocketClientProtocol) check with an attribute-based check for .closed.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

if (
self.ws is None
or (isinstance(self.ws, WebSocketClientProtocol) and self.ws.closed)
or (hasattr(self.ws, "closed") and self.ws.closed)
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.

2 participants