async def connect(self, on_stop=None, login=False): if self._connection is not None: raise APIConnectionError("Already connected!") connected = False stopped = False async def _on_stop(): nonlocal stopped if stopped: return stopped = True self._connection = None if connected and on_stop is not None: await on_stop() self._connection = APIConnection(self._params, _on_stop) try: await self._connection.connect() if login: await self._connection.login() except APIConnectionError: await _on_stop() raise except Exception as e: await _on_stop() raise APIConnectionError( "Unexpected error while connecting: {}".format(e)) connected = True
def conn(connection_params) -> APIConnection: async def on_stop(): pass return APIConnection(connection_params, on_stop)