When using connect_ws() or aconnect_ws(), if you don't pass a client instance, then a new client instance is created, but remains unclosed once the call returns.
It's a little awkward to get right, but the safest approach is to stick with with ... blocks for handling open/close of resources:
@contextlib.contextmanager
def connect_ws(...):
if client is None:
with httpx.Client(...) as client:
yield _connect_ws(..., client=client)
else:
yield _connect_ws(..., client=client)
@contextlib.contextmanager
def _connect_ws(...):
# main body of `connect_ws()`, but with a *mandatory* client argument.
Although you can also handle it with try...except:
@contextlib.contextmanager
def connect_ws(...):
should_close_client = False
if client is None:
client = ...
should_close_client = True
try:
... # main body of connect_ws()
finally:
if should_close_client:
client.close() # We only want to do this if we've created the client instance ourselves
When using
connect_ws()
oraconnect_ws()
, if you don't pass a client instance, then a new client instance is created, but remains unclosed once the call returns.It's a little awkward to get right, but the safest approach is to stick with
with ...
blocks for handling open/close of resources:Although you can also handle it with
try...except
: