From 6587ee20db2c5fc8d3e8b101abdd83f36c7388bd Mon Sep 17 00:00:00 2001 From: Sid <27780930+autinerd@users.noreply.github.com> Date: Sat, 30 Mar 2024 10:37:59 +0100 Subject: [PATCH] Enable Ruff TRY300 (#114437) * Enable Ruff TRY300 * Update validation.py * Address review comments --- .../components/amberelectric/config_flow.py | 9 ++++--- .../components/apple_tv/config_flow.py | 2 +- homeassistant/components/auth/indieauth.py | 2 +- homeassistant/components/awair/config_flow.py | 9 +++---- homeassistant/components/awair/coordinator.py | 2 +- homeassistant/components/buienradar/sensor.py | 9 ++++--- .../components/cert_expiry/config_flow.py | 3 ++- homeassistant/components/citybikes/sensor.py | 5 ++-- .../components/cloud/alexa_config.py | 5 +--- homeassistant/components/cloud/http_api.py | 2 +- .../components/command_line/utils.py | 21 ++++++++-------- .../components/control4/config_flow.py | 4 +-- homeassistant/components/deconz/hub/api.py | 2 +- homeassistant/components/dominos/__init__.py | 2 +- homeassistant/components/doorbird/camera.py | 5 ++-- homeassistant/components/dovado/__init__.py | 5 ++-- homeassistant/components/ebusd/__init__.py | 25 +++++++++---------- .../components/ecoforest/coordinator.py | 5 ++-- homeassistant/components/enocean/dongle.py | 2 +- .../components/enphase_envoy/coordinator.py | 4 +-- homeassistant/components/freebox/router.py | 2 +- homeassistant/components/fritz/common.py | 6 +++-- .../components/fritzbox/config_flow.py | 2 +- .../fritzbox_callmonitor/config_flow.py | 6 ++--- homeassistant/components/hassio/data.py | 12 ++++----- homeassistant/components/hassio/http.py | 10 +++----- homeassistant/components/heos/__init__.py | 5 ++-- .../components/hitron_coda/device_tracker.py | 2 +- .../components/homekit/type_cameras.py | 3 ++- homeassistant/components/homekit/util.py | 8 +++--- .../components/homematicip_cloud/hap.py | 4 +-- homeassistant/components/huawei_lte/sensor.py | 2 +- homeassistant/components/image/__init__.py | 2 +- homeassistant/components/imap/coordinator.py | 5 ++-- .../components/insteon/config_flow.py | 5 ++-- .../components/integration/sensor.py | 2 +- homeassistant/components/kef/media_player.py | 8 +++--- homeassistant/components/knx/validation.py | 22 ++++++++-------- homeassistant/components/litterrobot/hub.py | 1 - homeassistant/components/lyric/__init__.py | 2 +- .../components/meteoclimatic/__init__.py | 2 +- homeassistant/components/mikrotik/hub.py | 5 ++-- homeassistant/components/mysensors/gateway.py | 2 +- .../components/nextbus/coordinator.py | 2 +- .../components/nissan_leaf/__init__.py | 2 +- homeassistant/components/obihai/sensor.py | 12 ++++----- homeassistant/components/onvif/device.py | 3 ++- homeassistant/components/onvif/parsers.py | 2 +- .../components/owntracks/messages.py | 4 +-- .../components/panasonic_viera/__init__.py | 9 ++++--- .../components/picnic/coordinator.py | 6 ++--- homeassistant/components/ping/helpers.py | 2 +- .../components/prosegur/config_flow.py | 2 +- homeassistant/components/qvr_pro/camera.py | 17 ++++++------- homeassistant/components/recorder/core.py | 3 ++- .../components/recorder/migration.py | 10 +++++--- .../components/recorder/statistics.py | 2 +- homeassistant/components/recorder/util.py | 6 +++-- .../components/renault/coordinator.py | 5 ++-- homeassistant/components/roku/coordinator.py | 10 ++++---- .../components/rympro/coordinator.py | 2 +- .../components/shell_command/__init__.py | 2 +- homeassistant/components/sms/gateway.py | 2 +- .../components/solarlog/config_flow.py | 4 +-- .../components/spotify/media_player.py | 4 +-- homeassistant/components/ssdp/__init__.py | 3 ++- .../components/suez_water/__init__.py | 2 +- .../components/system_health/__init__.py | 3 ++- homeassistant/components/tcp/common.py | 2 +- .../components/telegram_bot/__init__.py | 3 ++- .../components/transmission/__init__.py | 5 ++-- homeassistant/components/unifi/hub/api.py | 3 ++- homeassistant/components/update/__init__.py | 2 +- homeassistant/components/vallox/__init__.py | 9 +++---- .../components/viaggiatreno/sensor.py | 4 ++- homeassistant/components/vicare/utils.py | 7 +++--- homeassistant/components/webhook/__init__.py | 2 +- homeassistant/components/wiz/__init__.py | 2 +- .../components/xiaomi_miio/device.py | 7 +++--- homeassistant/components/xiaomi_miio/light.py | 7 +++--- .../components/xiaomi_miio/remote.py | 2 +- .../components/xiaomi_miio/switch.py | 16 ++++++------ .../components/xiaomi_miio/vacuum.py | 2 +- homeassistant/components/zamg/weather.py | 6 ++--- homeassistant/components/zha/core/device.py | 19 +++++++------- homeassistant/components/zha/core/helpers.py | 2 +- homeassistant/config.py | 4 +-- homeassistant/config_entries.py | 5 ++-- homeassistant/core.py | 3 ++- homeassistant/helpers/config_validation.py | 6 ++--- homeassistant/helpers/entity_platform.py | 8 +++--- homeassistant/helpers/entity_registry.py | 5 ++-- homeassistant/helpers/intent.py | 2 +- homeassistant/helpers/network.py | 2 +- homeassistant/setup.py | 2 +- pyproject.toml | 3 +-- .../components/gardena_bluetooth/conftest.py | 2 +- 97 files changed, 259 insertions(+), 243 deletions(-) diff --git a/homeassistant/components/amberelectric/config_flow.py b/homeassistant/components/amberelectric/config_flow.py index 174e8716e0b..a94700c27d1 100644 --- a/homeassistant/components/amberelectric/config_flow.py +++ b/homeassistant/components/amberelectric/config_flow.py @@ -60,10 +60,6 @@ class AmberElectricConfigFlow(ConfigFlow, domain=DOMAIN): try: sites: list[Site] = filter_sites(api.get_sites()) - if len(sites) == 0: - self._errors[CONF_API_TOKEN] = "no_site" - return None - return sites except amberelectric.ApiException as api_exception: if api_exception.status == 403: self._errors[CONF_API_TOKEN] = "invalid_api_token" @@ -71,6 +67,11 @@ class AmberElectricConfigFlow(ConfigFlow, domain=DOMAIN): self._errors[CONF_API_TOKEN] = "unknown_error" return None + if len(sites) == 0: + self._errors[CONF_API_TOKEN] = "no_site" + return None + return sites + async def async_step_user( self, user_input: dict[str, str] | None = None ) -> ConfigFlowResult: diff --git a/homeassistant/components/apple_tv/config_flow.py b/homeassistant/components/apple_tv/config_flow.py index 19cbb24d8a2..f9be827741b 100644 --- a/homeassistant/components/apple_tv/config_flow.py +++ b/homeassistant/components/apple_tv/config_flow.py @@ -76,9 +76,9 @@ async def device_scan( return None try: ip_address(identifier) - return [identifier] except ValueError: return None + return [identifier] # If we have an address, only probe that address to avoid # broadcast traffic on the network diff --git a/homeassistant/components/auth/indieauth.py b/homeassistant/components/auth/indieauth.py index 232f067b673..45de94d5a70 100644 --- a/homeassistant/components/auth/indieauth.py +++ b/homeassistant/components/auth/indieauth.py @@ -127,9 +127,9 @@ def verify_client_id(client_id: str) -> bool: """Verify that the client id is valid.""" try: _parse_client_id(client_id) - return True except ValueError: return False + return True def _parse_url(url: str) -> ParseResult: diff --git a/homeassistant/components/awair/config_flow.py b/homeassistant/components/awair/config_flow.py index d3c4703e89c..a6efc3640f9 100644 --- a/homeassistant/components/awair/config_flow.py +++ b/homeassistant/components/awair/config_flow.py @@ -250,13 +250,12 @@ class AwairFlowHandler(ConfigFlow, domain=DOMAIN): try: user = await awair.user() devices = await user.devices() - if not devices: - return (None, "no_devices_found") - - return (user, None) - except AuthError: return (None, "invalid_access_token") except AwairError as err: LOGGER.error("Unexpected API error: %s", err) return (None, "unknown") + + if not devices: + return (None, "no_devices_found") + return (user, None) diff --git a/homeassistant/components/awair/coordinator.py b/homeassistant/components/awair/coordinator.py index 8e554b3b9e0..b63efff7733 100644 --- a/homeassistant/components/awair/coordinator.py +++ b/homeassistant/components/awair/coordinator.py @@ -111,7 +111,7 @@ class AwairLocalDataUpdateCoordinator(AwairDataUpdateCoordinator): devices = await self._awair.devices() self._device = devices[0] result = await self._fetch_air_data(self._device) - return {result.device.uuid: result} except AwairError as err: LOGGER.error("Unexpected API error: %s", err) raise UpdateFailed(err) from err + return {result.device.uuid: result} diff --git a/homeassistant/components/buienradar/sensor.py b/homeassistant/components/buienradar/sensor.py index fb15aa49001..69c762c1bc1 100644 --- a/homeassistant/components/buienradar/sensor.py +++ b/homeassistant/components/buienradar/sensor.py @@ -819,22 +819,23 @@ class BrSensor(SensorEntity): self._attr_native_value = data.get(FORECAST)[fcday].get( sensor_type[:-3] ) - if self.state is not None: - self._attr_native_value = round(self.state * 3.6, 1) - return True except IndexError: _LOGGER.warning("No forecast for fcday=%s", fcday) return False + if self.state is not None: + self._attr_native_value = round(self.state * 3.6, 1) + return True + # update all other sensors try: self._attr_native_value = data.get(FORECAST)[fcday].get( sensor_type[:-3] ) - return True except IndexError: _LOGGER.warning("No forecast for fcday=%s", fcday) return False + return True if sensor_type == SYMBOL or sensor_type.startswith(CONDITION): # update weather symbol & status text diff --git a/homeassistant/components/cert_expiry/config_flow.py b/homeassistant/components/cert_expiry/config_flow.py index 60863523553..8f937ef61ea 100644 --- a/homeassistant/components/cert_expiry/config_flow.py +++ b/homeassistant/components/cert_expiry/config_flow.py @@ -43,7 +43,6 @@ class CertexpiryConfigFlow(ConfigFlow, domain=DOMAIN): user_input[CONF_HOST], user_input.get(CONF_PORT, DEFAULT_PORT), ) - return True except ResolveFailed: self._errors[CONF_HOST] = "resolve_failed" except ConnectionTimeout: @@ -52,6 +51,8 @@ class CertexpiryConfigFlow(ConfigFlow, domain=DOMAIN): self._errors[CONF_HOST] = "connection_refused" except ValidationFailure: return True + else: + return True return False async def async_step_user( diff --git a/homeassistant/components/citybikes/sensor.py b/homeassistant/components/citybikes/sensor.py index 0cf27c20fa6..de85e6309f9 100644 --- a/homeassistant/components/citybikes/sensor.py +++ b/homeassistant/components/citybikes/sensor.py @@ -228,6 +228,9 @@ class CityBikesNetworks: self.hass, NETWORKS_URI, NETWORKS_RESPONSE_SCHEMA ) self.networks = networks[ATTR_NETWORKS_LIST] + except CityBikesRequestError as err: + raise PlatformNotReady from err + else: result = None minimum_dist = None for network in self.networks: @@ -241,8 +244,6 @@ class CityBikesNetworks: result = network[ATTR_ID] return result - except CityBikesRequestError as err: - raise PlatformNotReady from err finally: self.networks_loading.release() diff --git a/homeassistant/components/cloud/alexa_config.py b/homeassistant/components/cloud/alexa_config.py index 12f2b04d856..467d1589398 100644 --- a/homeassistant/components/cloud/alexa_config.py +++ b/homeassistant/components/cloud/alexa_config.py @@ -509,16 +509,13 @@ class CloudAlexaConfig(alexa_config.AbstractConfig): try: async with asyncio.timeout(10): await asyncio.wait(tasks, return_when=asyncio.ALL_COMPLETED) - - return True - except TimeoutError: _LOGGER.warning("Timeout trying to sync entities to Alexa") return False - except aiohttp.ClientError as err: _LOGGER.warning("Error trying to sync entities to Alexa: %s", err) return False + return True async def _handle_entity_registry_updated(self, event: Event) -> None: """Handle when entity registry updated.""" diff --git a/homeassistant/components/cloud/http_api.py b/homeassistant/components/cloud/http_api.py index 1a8fd7dbea9..8ca55876b28 100644 --- a/homeassistant/components/cloud/http_api.py +++ b/homeassistant/components/cloud/http_api.py @@ -135,12 +135,12 @@ def _handle_cloud_errors( """Handle exceptions that raise from the wrapped request handler.""" try: result = await handler(view, request, *args, **kwargs) - return result except Exception as err: # pylint: disable=broad-except status, msg = _process_cloud_exception(err, request.path) return view.json_message( msg, status_code=status, message_code=err.__class__.__name__.lower() ) + return result return error_handler diff --git a/homeassistant/components/command_line/utils.py b/homeassistant/components/command_line/utils.py index 067efc08e97..c1926546950 100644 --- a/homeassistant/components/command_line/utils.py +++ b/homeassistant/components/command_line/utils.py @@ -25,20 +25,21 @@ async def async_call_shell_with_timeout( ) async with asyncio.timeout(timeout): await proc.communicate() - return_code = proc.returncode - if return_code == _EXEC_FAILED_CODE: - _LOGGER.error("Error trying to exec command: %s", command) - elif log_return_code and return_code != 0: - _LOGGER.error( - "Command failed (with return code %s): %s", - proc.returncode, - command, - ) - return return_code or 0 except TimeoutError: _LOGGER.error("Timeout for command: %s", command) return -1 + return_code = proc.returncode + if return_code == _EXEC_FAILED_CODE: + _LOGGER.error("Error trying to exec command: %s", command) + elif log_return_code and return_code != 0: + _LOGGER.error( + "Command failed (with return code %s): %s", + proc.returncode, + command, + ) + return return_code or 0 + async def async_check_output_or_log(command: str, timeout: int) -> str | None: """Run a shell command with a timeout and return the output.""" diff --git a/homeassistant/components/control4/config_flow.py b/homeassistant/components/control4/config_flow.py index 2d7c6ade255..4ecc1ebe3f5 100644 --- a/homeassistant/components/control4/config_flow.py +++ b/homeassistant/components/control4/config_flow.py @@ -68,9 +68,9 @@ class Control4Validator: self.director_bearer_token = ( await account.getDirectorBearerToken(self.controller_unique_id) )["token"] - return True except (Unauthorized, NotFound): return False + return True async def connect_to_director(self) -> bool: """Test if we can connect to the local Control4 Director.""" @@ -82,10 +82,10 @@ class Control4Validator: self.host, self.director_bearer_token, director_session ) await director.getAllItemInfo() - return True except (Unauthorized, ClientError, TimeoutError): _LOGGER.error("Failed to connect to the Control4 controller") return False + return True class Control4ConfigFlow(ConfigFlow, domain=DOMAIN): diff --git a/homeassistant/components/deconz/hub/api.py b/homeassistant/components/deconz/hub/api.py index 71551ead6e1..916c34672d8 100644 --- a/homeassistant/components/deconz/hub/api.py +++ b/homeassistant/components/deconz/hub/api.py @@ -26,7 +26,6 @@ async def get_deconz_api( try: async with asyncio.timeout(10): await api.refresh_state() - return api except errors.Unauthorized as err: LOGGER.warning("Invalid key for deCONZ at %s", config.host) @@ -35,3 +34,4 @@ async def get_deconz_api( except (TimeoutError, errors.RequestError, errors.ResponseError) as err: LOGGER.error("Error connecting to deCONZ gateway at %s", config.host) raise CannotConnect from err + return api diff --git a/homeassistant/components/dominos/__init__.py b/homeassistant/components/dominos/__init__.py index 48404e6dbee..ce7b36f2280 100644 --- a/homeassistant/components/dominos/__init__.py +++ b/homeassistant/components/dominos/__init__.py @@ -139,10 +139,10 @@ class Dominos: """Update the shared closest store (if open).""" try: self.closest_store = self.address.closest_store() - return True except StoreException: self.closest_store = None return False + return True def get_menu(self): """Return the products from the closest stores menu.""" diff --git a/homeassistant/components/doorbird/camera.py b/homeassistant/components/doorbird/camera.py index ddc8ae0bdc5..961a3287799 100644 --- a/homeassistant/components/doorbird/camera.py +++ b/homeassistant/components/doorbird/camera.py @@ -107,8 +107,6 @@ class DoorBirdCamera(DoorBirdEntity, Camera): response = await websession.get(self._url) self._last_image = await response.read() - self._last_update = now - return self._last_image except TimeoutError: _LOGGER.error("DoorBird %s: Camera image timed out", self.name) return self._last_image @@ -118,6 +116,9 @@ class DoorBirdCamera(DoorBirdEntity, Camera): ) return self._last_image + self._last_update = now + return self._last_image + async def async_added_to_hass(self) -> None: """Subscribe to events.""" await super().async_added_to_hass() diff --git a/homeassistant/components/dovado/__init__.py b/homeassistant/components/dovado/__init__.py index 60e8351cc24..e89fd4361a5 100644 --- a/homeassistant/components/dovado/__init__.py +++ b/homeassistant/components/dovado/__init__.py @@ -74,10 +74,11 @@ class DovadoData: if not self.state: return False self.state.update(connected=self.state.get("modem status") == "CONNECTED") - _LOGGER.debug("Received: %s", self.state) - return True except OSError as error: _LOGGER.warning("Could not contact the router: %s", error) + return None + _LOGGER.debug("Received: %s", self.state) + return True @property def client(self): diff --git a/homeassistant/components/ebusd/__init__.py b/homeassistant/components/ebusd/__init__.py index debfc335496..c9386999fae 100644 --- a/homeassistant/components/ebusd/__init__.py +++ b/homeassistant/components/ebusd/__init__.py @@ -67,21 +67,20 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool: try: ebusdpy.init(server_address) - hass.data[DOMAIN] = EbusdData(server_address, circuit) - - sensor_config = { - CONF_MONITORED_CONDITIONS: monitored_conditions, - "client_name": name, - "sensor_types": SENSOR_TYPES[circuit], - } - load_platform(hass, Platform.SENSOR, DOMAIN, sensor_config, config) - - hass.services.register(DOMAIN, SERVICE_EBUSD_WRITE, hass.data[DOMAIN].write) - - _LOGGER.debug("Ebusd integration setup completed") - return True except (TimeoutError, OSError): return False + hass.data[DOMAIN] = EbusdData(server_address, circuit) + sensor_config = { + CONF_MONITORED_CONDITIONS: monitored_conditions, + "client_name": name, + "sensor_types": SENSOR_TYPES[circuit], + } + load_platform(hass, Platform.SENSOR, DOMAIN, sensor_config, config) + + hass.services.register(DOMAIN, SERVICE_EBUSD_WRITE, hass.data[DOMAIN].write) + + _LOGGER.debug("Ebusd integration setup completed") + return True class EbusdData: diff --git a/homeassistant/components/ecoforest/coordinator.py b/homeassistant/components/ecoforest/coordinator.py index ae0b353a1df..3b04325bd50 100644 --- a/homeassistant/components/ecoforest/coordinator.py +++ b/homeassistant/components/ecoforest/coordinator.py @@ -32,7 +32,8 @@ class EcoforestCoordinator(DataUpdateCoordinator[Device]): """Fetch all device and sensor data from api.""" try: data = await self.api.get() - _LOGGER.debug("Ecoforest data: %s", data) - return data except EcoforestError as err: raise UpdateFailed(f"Error communicating with API: {err}") from err + + _LOGGER.debug("Ecoforest data: %s", data) + return data diff --git a/homeassistant/components/enocean/dongle.py b/homeassistant/components/enocean/dongle.py index 6402b4c3a28..2d9a3f8787e 100644 --- a/homeassistant/components/enocean/dongle.py +++ b/homeassistant/components/enocean/dongle.py @@ -82,7 +82,7 @@ def validate_path(path: str): # Creating the serial communicator will raise an exception # if it cannot connect SerialCommunicator(port=path) - return True except serial.SerialException as exception: _LOGGER.warning("Dongle path %s is invalid: %s", path, str(exception)) return False + return True diff --git a/homeassistant/components/enphase_envoy/coordinator.py b/homeassistant/components/enphase_envoy/coordinator.py index c8152d44726..a508d5127d6 100644 --- a/homeassistant/components/enphase_envoy/coordinator.py +++ b/homeassistant/components/enphase_envoy/coordinator.py @@ -147,8 +147,6 @@ class EnphaseUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]): self._async_mark_setup_complete() # dump all received data in debug mode to assist troubleshooting envoy_data = await envoy.update() - _LOGGER.debug("Envoy data: %s", envoy_data) - return envoy_data.raw except INVALID_AUTH_ERRORS as err: if self._setup_complete and tries == 0: # token likely expired or firmware changed, try to re-authenticate @@ -157,5 +155,7 @@ class EnphaseUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]): raise ConfigEntryAuthFailed from err except EnvoyError as err: raise UpdateFailed(f"Error communicating with API: {err}") from err + _LOGGER.debug("Envoy data: %s", envoy_data) + return envoy_data.raw raise RuntimeError("Unreachable code in _async_update_data") # pragma: no cover diff --git a/homeassistant/components/freebox/router.py b/homeassistant/components/freebox/router.py index ef16a9df1b1..ed2fbcf1e83 100644 --- a/homeassistant/components/freebox/router.py +++ b/homeassistant/components/freebox/router.py @@ -43,7 +43,6 @@ def is_json(json_str: str) -> bool: """Validate if a String is a JSON value or not.""" try: json.loads(json_str) - return True except (ValueError, TypeError) as err: _LOGGER.error( "Failed to parse JSON '%s', error '%s'", @@ -51,6 +50,7 @@ def is_json(json_str: str) -> bool: err, ) return False + return True async def get_api(hass: HomeAssistant, host: str) -> Freepybox: diff --git a/homeassistant/components/fritz/common.py b/homeassistant/components/fritz/common.py index 8e773e74c75..b9d77220d7c 100644 --- a/homeassistant/components/fritz/common.py +++ b/homeassistant/components/fritz/common.py @@ -789,24 +789,26 @@ class AvmWrapper(FritzBoxTools): # pylint: disable=hass-enforce-coordinator-mod **kwargs, ) ) - return result except FritzSecurityError: _LOGGER.exception( "Authorization Error: Please check the provided credentials and" " verify that you can log into the web interface" ) + return {} except FRITZ_EXCEPTIONS: _LOGGER.exception( "Service/Action Error: cannot execute service %s with action %s", service_name, action_name, ) + return {} except FritzConnectionException: _LOGGER.exception( "Connection Error: Please check the device is properly configured" " for remote login" ) - return {} + return {} + return result async def async_get_upnp_configuration(self) -> dict[str, Any]: """Call X_AVM-DE_UPnP service.""" diff --git a/homeassistant/components/fritzbox/config_flow.py b/homeassistant/components/fritzbox/config_flow.py index 377d46eceff..fe4cf82b29b 100644 --- a/homeassistant/components/fritzbox/config_flow.py +++ b/homeassistant/components/fritzbox/config_flow.py @@ -82,13 +82,13 @@ class FritzboxConfigFlow(ConfigFlow, domain=DOMAIN): fritzbox.login() fritzbox.get_device_elements() fritzbox.logout() - return RESULT_SUCCESS except LoginError: return RESULT_INVALID_AUTH except HTTPError: return RESULT_NOT_SUPPORTED except OSError: return RESULT_NO_DEVICES_FOUND + return RESULT_SUCCESS async def async_step_user( self, user_input: dict[str, Any] | None = None diff --git a/homeassistant/components/fritzbox_callmonitor/config_flow.py b/homeassistant/components/fritzbox_callmonitor/config_flow.py index ac0d3ea3337..019326d840c 100644 --- a/homeassistant/components/fritzbox_callmonitor/config_flow.py +++ b/homeassistant/components/fritzbox_callmonitor/config_flow.py @@ -109,9 +109,6 @@ class FritzBoxCallMonitorConfigFlow(ConfigFlow, domain=DOMAIN): address=self._host, user=self._username, password=self._password ) info = fritz_connection.updatecheck - self._serial_number = info[FRITZ_ATTR_SERIAL_NUMBER] - - return ConnectResult.SUCCESS except RequestsConnectionError: return ConnectResult.NO_DEVIES_FOUND except FritzSecurityError: @@ -119,6 +116,9 @@ class FritzBoxCallMonitorConfigFlow(ConfigFlow, domain=DOMAIN): except FritzConnectionException: return ConnectResult.INVALID_AUTH + self._serial_number = info[FRITZ_ATTR_SERIAL_NUMBER] + return ConnectResult.SUCCESS + async def _get_name_of_phonebook(self, phonebook_id: int) -> str: """Return name of phonebook for given phonebook_id.""" phonebook_info = await self.hass.async_add_executor_job( diff --git a/homeassistant/components/hassio/data.py b/homeassistant/components/hassio/data.py index eaa7c2431fe..a00335d44a2 100644 --- a/homeassistant/components/hassio/data.py +++ b/homeassistant/components/hassio/data.py @@ -483,28 +483,28 @@ class HassioDataUpdateCoordinator(DataUpdateCoordinator): # pylint: disable=has """Update single addon stats.""" try: stats = await self.hassio.get_addon_stats(slug) - return (slug, stats) except HassioAPIError as err: _LOGGER.warning("Could not fetch stats for %s: %s", slug, err) - return (slug, None) + return (slug, None) + return (slug, stats) async def _update_addon_changelog(self, slug: str) -> tuple[str, str | None]: """Return the changelog for an add-on.""" try: changelog = await self.hassio.get_addon_changelog(slug) - return (slug, changelog) except HassioAPIError as err: _LOGGER.warning("Could not fetch changelog for %s: %s", slug, err) - return (slug, None) + return (slug, None) + return (slug, changelog) async def _update_addon_info(self, slug: str) -> tuple[str, dict[str, Any] | None]: """Return the info for an add-on.""" try: info = await self.hassio.get_addon_info(slug) - return (slug, info) except HassioAPIError as err: _LOGGER.warning("Could not fetch info for %s: %s", slug, err) - return (slug, None) + return (slug, None) + return (slug, info) @callback def async_enable_container_updates( diff --git a/homeassistant/components/hassio/http.py b/homeassistant/components/hassio/http.py index ffb67730fa5..826c7a27b98 100644 --- a/homeassistant/components/hassio/http.py +++ b/homeassistant/components/hassio/http.py @@ -188,15 +188,13 @@ class HassIOView(HomeAssistantView): async for data, _ in client.content.iter_chunks(): await response.write(data) - return response - except aiohttp.ClientError as err: _LOGGER.error("Client error on api %s request %s", path, err) - - except TimeoutError: + raise HTTPBadGateway from err + except TimeoutError as err: _LOGGER.error("Client timeout error on API request %s", path) - - raise HTTPBadGateway + raise HTTPBadGateway from err + return response get = _handle post = _handle diff --git a/homeassistant/components/heos/__init__.py b/homeassistant/components/heos/__init__.py index ed7c768e161..1573ff3f23e 100644 --- a/homeassistant/components/heos/__init__.py +++ b/homeassistant/components/heos/__init__.py @@ -478,7 +478,6 @@ class SourceManager: if controller.is_signed_in: favorites = await controller.get_favorites() inputs = await controller.get_input_sources() - return favorites, inputs except HeosError as error: if retry_attempts < self.max_retry_attempts: retry_attempts += 1 @@ -488,7 +487,9 @@ class SourceManager: await asyncio.sleep(self.retry_delay) else: _LOGGER.error("Unable to update sources: %s", error) - return + return None + else: + return favorites, inputs async def update_sources(event, data=None): if event in ( diff --git a/homeassistant/components/hitron_coda/device_tracker.py b/homeassistant/components/hitron_coda/device_tracker.py index ba672e38106..dec15e25b0b 100644 --- a/homeassistant/components/hitron_coda/device_tracker.py +++ b/homeassistant/components/hitron_coda/device_tracker.py @@ -95,10 +95,10 @@ class HitronCODADeviceScanner(DeviceScanner): return False try: self._userid = res.cookies["userid"] - return True except KeyError: _LOGGER.error("Failed to log in to router") return False + return True def _update_info(self): """Get ARP from router.""" diff --git a/homeassistant/components/homekit/type_cameras.py b/homeassistant/components/homekit/type_cameras.py index d47d9775ed2..5f1a9428d86 100644 --- a/homeassistant/components/homekit/type_cameras.py +++ b/homeassistant/components/homekit/type_cameras.py @@ -494,11 +494,12 @@ class Camera(HomeAccessory, PyhapCamera): # type: ignore[misc] _LOGGER.info("[%s] %s stream", session_id, shutdown_method) try: await getattr(stream, shutdown_method)() - return except Exception: # pylint: disable=broad-except _LOGGER.exception( "[%s] Failed to %s stream", session_id, shutdown_method ) + else: + return async def reconfigure_stream( self, session_info: dict[str, Any], stream_config: dict[str, Any] diff --git a/homeassistant/components/homekit/util.py b/homeassistant/components/homekit/util.py index 031cdbbc9bd..642669cfc8d 100644 --- a/homeassistant/components/homekit/util.py +++ b/homeassistant/components/homekit/util.py @@ -572,11 +572,12 @@ def _async_find_next_available_port(start_port: int, exclude_ports: set) -> int: continue try: test_socket.bind(("", port)) - return port except OSError: if port == MAX_PORT: raise continue + else: + return port raise RuntimeError("unreachable") @@ -584,10 +585,9 @@ def pid_is_alive(pid: int) -> bool: """Check to see if a process is alive.""" try: os.kill(pid, 0) - return True except OSError: - pass - return False + return False + return True def accessory_friendly_name(hass_name: str, accessory: Accessory) -> str: diff --git a/homeassistant/components/homematicip_cloud/hap.py b/homeassistant/components/homematicip_cloud/hap.py index 058b7ec6c00..7825999900e 100644 --- a/homeassistant/components/homematicip_cloud/hap.py +++ b/homeassistant/components/homematicip_cloud/hap.py @@ -39,9 +39,9 @@ class HomematicipAuth: self.auth = await self.get_auth( self.hass, self.config.get(HMIPC_HAPID), self.config.get(HMIPC_PIN) ) - return self.auth is not None except HmipcConnectionError: return False + return self.auth is not None async def async_checkbutton(self) -> bool: """Check blue butten has been pressed.""" @@ -55,9 +55,9 @@ class HomematicipAuth: try: authtoken = await self.auth.requestAuthToken() await self.auth.confirmAuthToken(authtoken) - return authtoken except HmipConnectionError: return False + return authtoken async def get_auth(self, hass: HomeAssistant, hapid, pin): """Create a HomematicIP access point object.""" diff --git a/homeassistant/components/huawei_lte/sensor.py b/homeassistant/components/huawei_lte/sensor.py index e75fef42ef3..cef5bc5030e 100644 --- a/homeassistant/components/huawei_lte/sensor.py +++ b/homeassistant/components/huawei_lte/sensor.py @@ -79,9 +79,9 @@ def format_last_reset_elapsed_seconds(value: str | None) -> datetime | None: try: last_reset = datetime.now() - timedelta(seconds=int(value)) last_reset.replace(microsecond=0) - return last_reset except ValueError: return None + return last_reset def signal_icon(limits: Sequence[int], value: StateType) -> str: diff --git a/homeassistant/components/image/__init__.py b/homeassistant/components/image/__init__.py index 47767a004cb..56dc7cc2cfa 100644 --- a/homeassistant/components/image/__init__.py +++ b/homeassistant/components/image/__init__.py @@ -199,7 +199,6 @@ class ImageEntity(Entity, cached_properties=CACHED_PROPERTIES_WITH_ATTR_): url, timeout=GET_IMAGE_TIMEOUT, follow_redirects=True ) response.raise_for_status() - return response except httpx.TimeoutException: _LOGGER.error("%s: Timeout getting image from %s", self.entity_id, url) return None @@ -211,6 +210,7 @@ class ImageEntity(Entity, cached_properties=CACHED_PROPERTIES_WITH_ATTR_): err, ) return None + return response async def _async_load_image_from_url(self, url: str) -> Image | None: """Load an image by url.""" diff --git a/homeassistant/components/imap/coordinator.py b/homeassistant/components/imap/coordinator.py index f7f2ef457c7..7f857ff857f 100644 --- a/homeassistant/components/imap/coordinator.py +++ b/homeassistant/components/imap/coordinator.py @@ -398,8 +398,6 @@ class ImapPollingDataUpdateCoordinator(ImapDataUpdateCoordinator): """Update the number of unread emails.""" try: messages = await self._async_fetch_number_of_messages() - self.auth_errors = 0 - return messages except ( AioImapException, UpdateFailed, @@ -426,6 +424,9 @@ class ImapPollingDataUpdateCoordinator(ImapDataUpdateCoordinator): self.async_set_update_error(ex) raise ConfigEntryAuthFailed from ex + self.auth_errors = 0 + return messages + class ImapPushDataUpdateCoordinator(ImapDataUpdateCoordinator): """Class for imap client.""" diff --git a/homeassistant/components/insteon/config_flow.py b/homeassistant/components/insteon/config_flow.py index 7eac51c600e..44aa1e18646 100644 --- a/homeassistant/components/insteon/config_flow.py +++ b/homeassistant/components/insteon/config_flow.py @@ -72,12 +72,13 @@ async def _async_connect(**kwargs): """Connect to the Insteon modem.""" try: await async_connect(**kwargs) - _LOGGER.info("Connected to Insteon modem") - return True except ConnectionError: _LOGGER.error("Could not connect to Insteon modem") return False + _LOGGER.info("Connected to Insteon modem") + return True + def _remove_override(address, options): """Remove a device override from config.""" diff --git a/homeassistant/components/integration/sensor.py b/homeassistant/components/integration/sensor.py index 62a0dbdec78..ef587e405e6 100644 --- a/homeassistant/components/integration/sensor.py +++ b/homeassistant/components/integration/sensor.py @@ -145,9 +145,9 @@ class _Right(_IntegrationMethod): def _is_numeric_state(state: State) -> bool: try: float(state.state) - return True except (ValueError, TypeError): return False + return True _NAME_TO_INTEGRATION_METHOD: dict[str, type[_IntegrationMethod]] = { diff --git a/homeassistant/components/kef/media_player.py b/homeassistant/components/kef/media_player.py index d7d33dabd44..04ecd633d70 100644 --- a/homeassistant/components/kef/media_player.py +++ b/homeassistant/components/kef/media_player.py @@ -79,12 +79,14 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( def get_ip_mode(host): """Get the 'mode' used to retrieve the MAC address.""" try: - if ipaddress.ip_address(host).version == 6: - return "ip6" - return "ip" + ip_address = ipaddress.ip_address(host) except ValueError: return "hostname" + if ip_address.version == 6: + return "ip6" + return "ip" + async def async_setup_platform( hass: HomeAssistant, diff --git a/homeassistant/components/knx/validation.py b/homeassistant/components/knx/validation.py index 9fe87a2c3f6..4e56314a677 100644 --- a/homeassistant/components/knx/validation.py +++ b/homeassistant/components/knx/validation.py @@ -37,17 +37,17 @@ string_type_validator = dpt_subclass_validator(DPTString) def ga_validator(value: Any) -> str | int: """Validate that value is parsable as GroupAddress or InternalGroupAddress.""" - if isinstance(value, (str, int)): - try: - parse_device_group_address(value) - return value - except CouldNotParseAddress as exc: - raise vol.Invalid( - f"'{value}' is not a valid KNX group address: {exc.message}" - ) from exc - raise vol.Invalid( - f"'{value}' is not a valid KNX group address: Invalid type '{type(value).__name__}'" - ) + if not isinstance(value, (str, int)): + raise vol.Invalid( + f"'{value}' is not a valid KNX group address: Invalid type '{type(value).__name__}'" + ) + try: + parse_device_group_address(value) + except CouldNotParseAddress as exc: + raise vol.Invalid( + f"'{value}' is not a valid KNX group address: {exc.message}" + ) from exc + return value ga_list_validator = vol.All( diff --git a/homeassistant/components/litterrobot/hub.py b/homeassistant/components/litterrobot/hub.py index 4af004bddf5..2e31bcf9906 100644 --- a/homeassistant/components/litterrobot/hub.py +++ b/homeassistant/components/litterrobot/hub.py @@ -55,7 +55,6 @@ class LitterRobotHub: load_robots=load_robots, subscribe_for_updates=subscribe_for_updates, ) - return except LitterRobotLoginException as ex: raise ConfigEntryAuthFailed("Invalid credentials") from ex except LitterRobotException as ex: diff --git a/homeassistant/components/lyric/__init__.py b/homeassistant/components/lyric/__init__.py index e2c85c1400b..84ef3a2b7db 100644 --- a/homeassistant/components/lyric/__init__.py +++ b/homeassistant/components/lyric/__init__.py @@ -77,7 +77,6 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: try: async with asyncio.timeout(60): await lyric.get_locations() - return lyric except LyricAuthenticationException as exception: # Attempt to refresh the token before failing. # Honeywell appear to have issues keeping tokens saved. @@ -87,6 +86,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: raise ConfigEntryAuthFailed from exception except (LyricException, ClientResponseError) as exception: raise UpdateFailed(exception) from exception + return lyric coordinator = DataUpdateCoordinator[Lyric]( hass, diff --git a/homeassistant/components/meteoclimatic/__init__.py b/homeassistant/components/meteoclimatic/__init__.py index 1e729258218..2c371ebdcfd 100644 --- a/homeassistant/components/meteoclimatic/__init__.py +++ b/homeassistant/components/meteoclimatic/__init__.py @@ -25,9 +25,9 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: data = await hass.async_add_executor_job( meteoclimatic_client.weather_at_station, station_code ) - return data.__dict__ except MeteoclimaticError as err: raise UpdateFailed(f"Error while retrieving data: {err}") from err + return data.__dict__ coordinator = DataUpdateCoordinator( hass, diff --git a/homeassistant/components/mikrotik/hub.py b/homeassistant/components/mikrotik/hub.py index 6b94a621683..2830372f882 100644 --- a/homeassistant/components/mikrotik/hub.py +++ b/homeassistant/components/mikrotik/hub.py @@ -325,8 +325,6 @@ def get_api(entry: dict[str, Any]) -> librouteros.Api: entry[CONF_PASSWORD], **kwargs, ) - _LOGGER.debug("Connected to %s successfully", entry[CONF_HOST]) - return api except ( librouteros.exceptions.LibRouterosError, OSError, @@ -336,3 +334,6 @@ def get_api(entry: dict[str, Any]) -> librouteros.Api: if "invalid user name or password" in str(api_error): raise LoginError from api_error raise CannotConnect from api_error + + _LOGGER.debug("Connected to %s successfully", entry[CONF_HOST]) + return api diff --git a/homeassistant/components/mysensors/gateway.py b/homeassistant/components/mysensors/gateway.py index b932a33d0fa..8e9fb5442ea 100644 --- a/homeassistant/components/mysensors/gateway.py +++ b/homeassistant/components/mysensors/gateway.py @@ -71,9 +71,9 @@ def is_socket_address(value: str) -> str: """Validate that value is a valid address.""" try: socket.getaddrinfo(value, None) - return value except OSError as err: raise vol.Invalid("Device is not a valid domain name or ip address") from err + return value async def try_connect( diff --git a/homeassistant/components/nextbus/coordinator.py b/homeassistant/components/nextbus/coordinator.py index abf280bece9..15377bce56b 100644 --- a/homeassistant/components/nextbus/coordinator.py +++ b/homeassistant/components/nextbus/coordinator.py @@ -72,8 +72,8 @@ class NextBusDataUpdateCoordinator(DataUpdateCoordinator): # Casting here because we expect dict and not a str due to the input format selected being JSON data = cast(dict[str, Any], data) self._calc_predictions(data) - return data except (NextBusHTTPError, NextBusFormatError) as ex: raise UpdateFailed("Failed updating nextbus data", ex) from ex + return data return await self.hass.async_add_executor_job(_update_data) diff --git a/homeassistant/components/nissan_leaf/__init__.py b/homeassistant/components/nissan_leaf/__init__.py index 9eaca66119f..2cbec236261 100644 --- a/homeassistant/components/nissan_leaf/__init__.py +++ b/homeassistant/components/nissan_leaf/__init__.py @@ -418,13 +418,13 @@ class LeafDataStore: server_info = await self.hass.async_add_executor_job( self.leaf.get_latest_battery_status ) - return server_info except CarwingsError: _LOGGER.error("An error occurred getting battery status") return None except (KeyError, TypeError): _LOGGER.error("An error occurred parsing response from server") return None + return server_info async def async_get_climate( self, diff --git a/homeassistant/components/obihai/sensor.py b/homeassistant/components/obihai/sensor.py index 91920b4c32d..344767c8cd1 100644 --- a/homeassistant/components/obihai/sensor.py +++ b/homeassistant/components/obihai/sensor.py @@ -109,15 +109,15 @@ class ObihaiServiceSensors(SensorEntity): LOGGER.info("Connection restored") self._attr_available = True - return - except RequestException as exc: if self.requester.available: LOGGER.warning("Connection failed, Obihai offline? %s", exc) + self._attr_native_value = None + self._attr_available = False + self.requester.available = False except IndexError as exc: if self.requester.available: LOGGER.warning("Connection failed, bad response: %s", exc) - - self._attr_native_value = None - self._attr_available = False - self.requester.available = False + self._attr_native_value = None + self._attr_available = False + self.requester.available = False diff --git a/homeassistant/components/onvif/device.py b/homeassistant/components/onvif/device.py index 71acf62f97d..b427cbda2f8 100644 --- a/homeassistant/components/onvif/device.py +++ b/homeassistant/components/onvif/device.py @@ -218,12 +218,13 @@ class ONVIFDevice: try: await device_mgmt.SetSystemDateAndTime(dt_param) LOGGER.debug("%s: SetSystemDateAndTime: success", self.name) - return # Some cameras don't support setting the timezone and will throw an IndexError # if we try to set it. If we get an error, try again without the timezone. except (IndexError, Fault): if idx == timezone_max_idx: raise + else: + return async def async_check_date_and_time(self) -> None: """Warns if device and system date not synced.""" diff --git a/homeassistant/components/onvif/parsers.py b/homeassistant/components/onvif/parsers.py index 690a3739b4f..29da0fee35f 100644 --- a/homeassistant/components/onvif/parsers.py +++ b/homeassistant/components/onvif/parsers.py @@ -221,9 +221,9 @@ async def async_parse_field_detector(uid: str, msg) -> Event | None: None, payload.Data.SimpleItem[0].Value == "true", ) - return evt except (AttributeError, KeyError): return None + return evt @PARSERS.register("tns1:RuleEngine/CellMotionDetector/Motion") diff --git a/homeassistant/components/owntracks/messages.py b/homeassistant/components/owntracks/messages.py index 3e669079848..011b4f75489 100644 --- a/homeassistant/components/owntracks/messages.py +++ b/homeassistant/components/owntracks/messages.py @@ -135,8 +135,6 @@ def _decrypt_payload(secret, topic, ciphertext): try: message = decrypt(ciphertext, key) message = message.decode("utf-8") - _LOGGER.debug("Decrypted payload: %s", message) - return message except ValueError: _LOGGER.warning( ( @@ -146,6 +144,8 @@ def _decrypt_payload(secret, topic, ciphertext): topic, ) return None + _LOGGER.debug("Decrypted payload: %s", message) + return message def encrypt_message(secret, topic, message): diff --git a/homeassistant/components/panasonic_viera/__init__.py b/homeassistant/components/panasonic_viera/__init__.py index 8ec825c5974..5c76a7e6900 100644 --- a/homeassistant/components/panasonic_viera/__init__.py +++ b/homeassistant/components/panasonic_viera/__init__.py @@ -247,9 +247,6 @@ class Remote: """Handle errors from func, set available and reconnect if needed.""" try: result = await self._hass.async_add_executor_job(func, *args) - self.state = STATE_ON - self.available = True - return result except EncryptionRequired: _LOGGER.error( "The connection couldn't be encrypted. Please reconfigure your TV" @@ -260,12 +257,18 @@ class Remote: self.state = STATE_OFF self.available = True await self.async_create_remote_control() + return None except (URLError, OSError) as err: _LOGGER.debug("An error occurred: %s", err) self.state = STATE_OFF self.available = self._on_action is not None await self.async_create_remote_control() + return None except Exception: # pylint: disable=broad-except _LOGGER.exception("An unknown error occurred") self.state = STATE_OFF self.available = self._on_action is not None + return None + self.state = STATE_ON + self.available = True + return result diff --git a/homeassistant/components/picnic/coordinator.py b/homeassistant/components/picnic/coordinator.py index 7a76d3174cd..c367d5ec548 100644 --- a/homeassistant/components/picnic/coordinator.py +++ b/homeassistant/components/picnic/coordinator.py @@ -50,14 +50,14 @@ class PicnicUpdateCoordinator(DataUpdateCoordinator): # Update the auth token in the config entry if applicable self._update_auth_token() - - # Return the fetched data - return data except ValueError as error: raise UpdateFailed(f"API response was malformed: {error}") from error except PicnicAuthError as error: raise ConfigEntryAuthFailed from error + # Return the fetched data + return data + def fetch_data(self): """Fetch the data from the Picnic API and return a flat dict with only needed sensor data.""" # Fetch from the API and pre-process the data diff --git a/homeassistant/components/ping/helpers.py b/homeassistant/components/ping/helpers.py index f9afcef7be9..f1fd8518d42 100644 --- a/homeassistant/components/ping/helpers.py +++ b/homeassistant/components/ping/helpers.py @@ -140,7 +140,6 @@ class PingDataSubProcess(PingData): if TYPE_CHECKING: assert match is not None rtt_min, rtt_avg, rtt_max, rtt_mdev = match.groups() - return {"min": rtt_min, "avg": rtt_avg, "max": rtt_max, "mdev": rtt_mdev} except TimeoutError: _LOGGER.exception( "Timed out running command: `%s`, after: %ss", @@ -155,6 +154,7 @@ class PingDataSubProcess(PingData): return None except AttributeError: return None + return {"min": rtt_min, "avg": rtt_avg, "max": rtt_max, "mdev": rtt_mdev} async def async_update(self) -> None: """Retrieve the latest details from the host.""" diff --git a/homeassistant/components/prosegur/config_flow.py b/homeassistant/components/prosegur/config_flow.py index 36d1ae9d10f..911ae6104fd 100644 --- a/homeassistant/components/prosegur/config_flow.py +++ b/homeassistant/components/prosegur/config_flow.py @@ -35,11 +35,11 @@ async def validate_input(hass: HomeAssistant, data): auth = Auth(session, data[CONF_USERNAME], data[CONF_PASSWORD], data[CONF_COUNTRY]) try: contracts = await Installation.list(auth) - return auth, contracts except ConnectionRefusedError: raise InvalidAuth from ConnectionRefusedError except ConnectionError: raise CannotConnect from ConnectionError + return auth, contracts class ProsegurConfigFlow(ConfigFlow, domain=DOMAIN): diff --git a/homeassistant/components/qvr_pro/camera.py b/homeassistant/components/qvr_pro/camera.py index 544ef808ca7..2754ab3a1ec 100644 --- a/homeassistant/components/qvr_pro/camera.py +++ b/homeassistant/components/qvr_pro/camera.py @@ -43,19 +43,18 @@ def get_stream_source(guid, client): """Get channel stream source.""" try: resp = client.get_channel_live_stream(guid, protocol="rtsp") - - full_url = resp["resourceUris"] - - protocol = full_url[:7] - auth = f"{client.get_auth_string()}@" - url = full_url[7:] - - return f"{protocol}{auth}{url}" - except QVRResponseError as ex: _LOGGER.error(ex) return None + full_url = resp["resourceUris"] + + protocol = full_url[:7] + auth = f"{client.get_auth_string()}@" + url = full_url[7:] + + return f"{protocol}{auth}{url}" + class QVRProCamera(Camera): """Representation of a QVR Pro camera.""" diff --git a/homeassistant/components/recorder/core.py b/homeassistant/components/recorder/core.py index 3268bae4d49..4ae61a0c4ba 100644 --- a/homeassistant/components/recorder/core.py +++ b/homeassistant/components/recorder/core.py @@ -1179,7 +1179,6 @@ class Recorder(threading.Thread): while tries <= self.db_max_retries: try: self._commit_event_session() - return except (exc.InternalError, exc.OperationalError) as err: _LOGGER.error( "%s: Error executing query: %s. (retrying in %s seconds)", @@ -1192,6 +1191,8 @@ class Recorder(threading.Thread): tries += 1 time.sleep(self.db_retry_wait) + else: + return def _commit_event_session(self) -> None: assert self.event_session is not None diff --git a/homeassistant/components/recorder/migration.py b/homeassistant/components/recorder/migration.py index 0d882ed3b66..630628b2045 100644 --- a/homeassistant/components/recorder/migration.py +++ b/homeassistant/components/recorder/migration.py @@ -341,10 +341,10 @@ def _execute_or_collect_error( with session_scope(session=session_maker()) as session: try: session.connection().execute(text(query)) - return True except SQLAlchemyError as err: errors.append(str(err)) - return False + return False + return True def _drop_index( @@ -439,11 +439,12 @@ def _add_columns( ) ) ) - return except (InternalError, OperationalError, ProgrammingError): # Some engines support adding all columns at once, # this error is when they don't _LOGGER.info("Unable to use quick column add. Adding 1 by 1") + else: + return for column_def in columns_def: with session_scope(session=session_maker()) as session: @@ -510,9 +511,10 @@ def _modify_columns( ) ) ) - return except (InternalError, OperationalError): _LOGGER.info("Unable to use quick column modify. Modifying 1 by 1") + else: + return for column_def in columns_def: with session_scope(session=session_maker()) as session: diff --git a/homeassistant/components/recorder/statistics.py b/homeassistant/components/recorder/statistics.py index f840fdbd7b6..0c127d079ad 100644 --- a/homeassistant/components/recorder/statistics.py +++ b/homeassistant/components/recorder/statistics.py @@ -641,7 +641,6 @@ def _insert_statistics( try: stat = table.from_stats(metadata_id, statistic) session.add(stat) - return stat except SQLAlchemyError: _LOGGER.exception( "Unexpected exception when inserting statistics %s:%s ", @@ -649,6 +648,7 @@ def _insert_statistics( statistic, ) return None + return stat def _update_statistics( diff --git a/homeassistant/components/recorder/util.py b/homeassistant/components/recorder/util.py index 77467ec1171..ad96833b1d7 100644 --- a/homeassistant/components/recorder/util.py +++ b/homeassistant/components/recorder/util.py @@ -192,13 +192,14 @@ def execute( elapsed, ) - return result except SQLAlchemyError as err: _LOGGER.error("Error executing query: %s", err) if tryno == RETRIES - 1: raise time.sleep(QUERY_RETRY_WAIT) + else: + return result # Unreachable raise RuntimeError # pragma: no cover @@ -685,7 +686,6 @@ def database_job_retry_wrapper( for attempt in range(attempts): try: job(instance, *args, **kwargs) - return except OperationalError as err: if attempt == attempts - 1 or not _is_retryable_error( instance, err @@ -697,6 +697,8 @@ def database_job_retry_wrapper( ) time.sleep(instance.db_retry_wait) # Failed with retryable error + else: + return return wrapper diff --git a/homeassistant/components/renault/coordinator.py b/homeassistant/components/renault/coordinator.py index f77a38f2505..d7aed6e3560 100644 --- a/homeassistant/components/renault/coordinator.py +++ b/homeassistant/components/renault/coordinator.py @@ -55,8 +55,6 @@ class RenaultDataUpdateCoordinator(DataUpdateCoordinator[T]): try: async with _PARALLEL_SEMAPHORE: data = await self.update_method() - self._has_already_worked = True - return data except AccessDeniedException as err: # This can mean both a temporary error or a permanent error. If it has @@ -76,6 +74,9 @@ class RenaultDataUpdateCoordinator(DataUpdateCoordinator[T]): # Other Renault errors. raise UpdateFailed(f"Error communicating with API: {err}") from err + self._has_already_worked = True + return data + async def async_config_entry_first_refresh(self) -> None: """Refresh data for the first time when a config entry is setup. diff --git a/homeassistant/components/roku/coordinator.py b/homeassistant/components/roku/coordinator.py index baef00b2596..303d0e91a36 100644 --- a/homeassistant/components/roku/coordinator.py +++ b/homeassistant/components/roku/coordinator.py @@ -62,10 +62,10 @@ class RokuDataUpdateCoordinator(DataUpdateCoordinator[Device]): try: data = await self.roku.update(full_update=full_update) - - if full_update: - self.last_full_update = utcnow() - - return data except RokuError as error: raise UpdateFailed(f"Invalid response from API: {error}") from error + + if full_update: + self.last_full_update = utcnow() + + return data diff --git a/homeassistant/components/rympro/coordinator.py b/homeassistant/components/rympro/coordinator.py index f2e5162a0f0..19f16005578 100644 --- a/homeassistant/components/rympro/coordinator.py +++ b/homeassistant/components/rympro/coordinator.py @@ -39,10 +39,10 @@ class RymProDataUpdateCoordinator(DataUpdateCoordinator[dict[int, dict]]): meter["consumption_forecast"] = await self.rympro.consumption_forecast( meter_id ) - return meters except UnauthorizedError as error: assert self.config_entry await self.hass.config_entries.async_reload(self.config_entry.entry_id) raise UpdateFailed(error) from error except (CannotConnectError, OperationError) as error: raise UpdateFailed(error) from error + return meters diff --git a/homeassistant/components/shell_command/__init__.py b/homeassistant/components/shell_command/__init__.py index 736654fc399..95bbb01bcfb 100644 --- a/homeassistant/components/shell_command/__init__.py +++ b/homeassistant/components/shell_command/__init__.py @@ -135,12 +135,12 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: service_response["stdout"] = stdout_data.decode("utf-8").strip() if stderr_data: service_response["stderr"] = stderr_data.decode("utf-8").strip() - return service_response except UnicodeDecodeError: _LOGGER.exception( "Unable to handle non-utf8 output of command: `%s`", cmd ) raise + return service_response return None for name in conf: diff --git a/homeassistant/components/sms/gateway.py b/homeassistant/components/sms/gateway.py index 50abc9b39ef..9b5b8c1f51e 100644 --- a/homeassistant/components/sms/gateway.py +++ b/homeassistant/components/sms/gateway.py @@ -210,7 +210,7 @@ async def create_sms_gateway(config, hass): _LOGGER.error("Failed to initialize, error %s", exc) await gateway.terminate_async() return None - return gateway except gammu.GSMError as exc: _LOGGER.error("Failed to create async worker, error %s", exc) return None + return gateway diff --git a/homeassistant/components/solarlog/config_flow.py b/homeassistant/components/solarlog/config_flow.py index 83b9c600de8..40343b5ac12 100644 --- a/homeassistant/components/solarlog/config_flow.py +++ b/homeassistant/components/solarlog/config_flow.py @@ -44,14 +44,14 @@ class SolarLogConfigFlow(ConfigFlow, domain=DOMAIN): """Check if we can connect to the Solar-Log device.""" try: await self.hass.async_add_executor_job(SolarLog, host) - return True except (OSError, HTTPError, Timeout): self._errors[CONF_HOST] = "cannot_connect" _LOGGER.error( "Could not connect to Solar-Log device at %s, check host ip address", host, ) - return False + return False + return True async def async_step_user(self, user_input=None): """Step when user initializes a integration.""" diff --git a/homeassistant/components/spotify/media_player.py b/homeassistant/components/spotify/media_player.py index 487e58d8f8b..2e725e8d139 100644 --- a/homeassistant/components/spotify/media_player.py +++ b/homeassistant/components/spotify/media_player.py @@ -101,8 +101,6 @@ def spotify_exception_handler( # pylint: disable=protected-access try: result = func(self, *args, **kwargs) - self._attr_available = True - return result except requests.RequestException: self._attr_available = False return None @@ -111,6 +109,8 @@ def spotify_exception_handler( if exc.reason == "NO_ACTIVE_DEVICE": raise HomeAssistantError("No active playback device found") from None raise HomeAssistantError(f"Spotify error: {exc.reason}") from exc + self._attr_available = True + return result return wrapper diff --git a/homeassistant/components/ssdp/__init__.py b/homeassistant/components/ssdp/__init__.py index b34105106e0..08d1bbb858e 100644 --- a/homeassistant/components/ssdp/__init__.py +++ b/homeassistant/components/ssdp/__init__.py @@ -735,10 +735,11 @@ async def _async_find_next_available_port(source: AddressTupleVXType) -> int: addr = (source[0],) + (port,) + source[2:] try: test_socket.bind(addr) - return port except OSError: if port == UPNP_SERVER_MAX_PORT - 1: raise + else: + return port raise RuntimeError("unreachable") diff --git a/homeassistant/components/suez_water/__init__.py b/homeassistant/components/suez_water/__init__.py index 07944de2c81..f5b2880e011 100644 --- a/homeassistant/components/suez_water/__init__.py +++ b/homeassistant/components/suez_water/__init__.py @@ -28,9 +28,9 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: ) if not client.check_credentials(): raise ConfigEntryError - return client except PySuezError as ex: raise ConfigEntryNotReady from ex + return client hass.data.setdefault(DOMAIN, {})[ entry.entry_id diff --git a/homeassistant/components/system_health/__init__.py b/homeassistant/components/system_health/__init__.py index 6a1e4830443..f61745a1407 100644 --- a/homeassistant/components/system_health/__init__.py +++ b/homeassistant/components/system_health/__init__.py @@ -235,11 +235,12 @@ async def async_check_can_reach_url( try: await session.get(url, timeout=5) - return "ok" except aiohttp.ClientError: data = {"type": "failed", "error": "unreachable"} except TimeoutError: data = {"type": "failed", "error": "timeout"} + else: + return "ok" if more_info is not None: data["more_info"] = more_info return data diff --git a/homeassistant/components/tcp/common.py b/homeassistant/components/tcp/common.py index 46520134bf6..d6a7fb28f11 100644 --- a/homeassistant/components/tcp/common.py +++ b/homeassistant/components/tcp/common.py @@ -149,7 +149,6 @@ class TcpEntity(Entity): if value_template is not None: try: self._state = value_template.render(parse_result=False, value=value) - return except TemplateError: _LOGGER.error( "Unable to render template of %r with value: %r", @@ -157,5 +156,6 @@ class TcpEntity(Entity): value, ) return + return self._state = value diff --git a/homeassistant/components/telegram_bot/__init__.py b/homeassistant/components/telegram_bot/__init__.py index 6338996256b..4e47be8b807 100644 --- a/homeassistant/components/telegram_bot/__init__.py +++ b/homeassistant/components/telegram_bot/__init__.py @@ -687,11 +687,12 @@ class TelegramNotificationService: _LOGGER.warning( "Update last message: out_type:%s, out=%s", type(out), out ) - return out except TelegramError as exc: _LOGGER.error( "%s: %s. Args: %s, kwargs: %s", msg_error, exc, args_msg, kwargs_msg ) + return None + return out async def send_message(self, message="", target=None, **kwargs): """Send a message to one or multiple pre-allowed chat IDs.""" diff --git a/homeassistant/components/transmission/__init__.py b/homeassistant/components/transmission/__init__.py index 4dcc4d41950..d7d6ae4ea0c 100644 --- a/homeassistant/components/transmission/__init__.py +++ b/homeassistant/components/transmission/__init__.py @@ -267,9 +267,6 @@ async def get_api( path=path, ) ) - _LOGGER.debug("Successfully connected to %s", host) - return api - except TransmissionAuthError as error: _LOGGER.error("Credentials for Transmission client are not valid") raise AuthenticationError from error @@ -279,3 +276,5 @@ async def get_api( except TransmissionError as error: _LOGGER.error(error) raise UnknownError from error + _LOGGER.debug("Successfully connected to %s", host) + return api diff --git a/homeassistant/components/unifi/hub/api.py b/homeassistant/components/unifi/hub/api.py index 8a1be0427b2..acdd941dd15 100644 --- a/homeassistant/components/unifi/hub/api.py +++ b/homeassistant/components/unifi/hub/api.py @@ -56,7 +56,6 @@ async def get_unifi_api( try: async with asyncio.timeout(10): await api.login() - return api except aiounifi.Unauthorized as err: LOGGER.warning( @@ -90,3 +89,5 @@ async def get_unifi_api( except aiounifi.AiounifiException as err: LOGGER.exception("Unknown UniFi Network communication error occurred: %s", err) raise AuthenticationRequired from err + + return api diff --git a/homeassistant/components/update/__init__.py b/homeassistant/components/update/__init__.py index f274da6f412..142c9b4a6c3 100644 --- a/homeassistant/components/update/__init__.py +++ b/homeassistant/components/update/__init__.py @@ -408,10 +408,10 @@ class UpdateEntity( try: newer = _version_is_newer(latest_version, installed_version) - return STATE_ON if newer else STATE_OFF except AwesomeVersionCompareException: # Can't compare versions, already tried exact match return STATE_ON + return STATE_ON if newer else STATE_OFF @final @property diff --git a/homeassistant/components/vallox/__init__.py b/homeassistant/components/vallox/__init__.py index 7c9234d35c2..b8e94e9dfb7 100644 --- a/homeassistant/components/vallox/__init__.py +++ b/homeassistant/components/vallox/__init__.py @@ -175,11 +175,10 @@ class ValloxServiceHandler: try: await self._client.set_fan_speed(Profile.HOME, fan_speed) - return True - except ValloxApiException as err: _LOGGER.error("Error setting fan speed for Home profile: %s", err) return False + return True async def async_set_profile_fan_speed_away( self, fan_speed: int = DEFAULT_FAN_SPEED_AWAY @@ -189,11 +188,10 @@ class ValloxServiceHandler: try: await self._client.set_fan_speed(Profile.AWAY, fan_speed) - return True - except ValloxApiException as err: _LOGGER.error("Error setting fan speed for Away profile: %s", err) return False + return True async def async_set_profile_fan_speed_boost( self, fan_speed: int = DEFAULT_FAN_SPEED_BOOST @@ -203,11 +201,10 @@ class ValloxServiceHandler: try: await self._client.set_fan_speed(Profile.BOOST, fan_speed) - return True - except ValloxApiException as err: _LOGGER.error("Error setting fan speed for Boost profile: %s", err) return False + return True async def async_handle(self, call: ServiceCall) -> None: """Dispatch a service call.""" diff --git a/homeassistant/components/viaggiatreno/sensor.py b/homeassistant/components/viaggiatreno/sensor.py index 3738b0f956a..9c6c6bca422 100644 --- a/homeassistant/components/viaggiatreno/sensor.py +++ b/homeassistant/components/viaggiatreno/sensor.py @@ -84,11 +84,13 @@ async def async_http_request(hass, uri): if req.status != HTTPStatus.OK: return {"error": req.status} json_response = await req.json() - return json_response except (TimeoutError, aiohttp.ClientError) as exc: _LOGGER.error("Cannot connect to ViaggiaTreno API endpoint: %s", exc) + return None except ValueError: _LOGGER.error("Received non-JSON data from ViaggiaTreno API endpoint") + return None + return json_response class ViaggiaTrenoSensor(SensorEntity): diff --git a/homeassistant/components/vicare/utils.py b/homeassistant/components/vicare/utils.py index 2019f28a896..2ba5ddbfb0a 100644 --- a/homeassistant/components/vicare/utils.py +++ b/homeassistant/components/vicare/utils.py @@ -35,13 +35,14 @@ def is_supported( """Check if the PyViCare device supports the requested sensor.""" try: entity_description.value_getter(vicare_device) - _LOGGER.debug("Found entity %s", name) - return True except PyViCareNotSupportedFeatureError: _LOGGER.debug("Feature not supported %s", name) + return False except AttributeError as error: _LOGGER.debug("Feature not supported %s: %s", name, error) - return False + return False + _LOGGER.debug("Found entity %s", name) + return True def get_burners(device: PyViCareDevice) -> list[PyViCareHeatingDeviceComponent]: diff --git a/homeassistant/components/webhook/__init__.py b/homeassistant/components/webhook/__init__.py index f2d1416e2c9..0076c85e268 100644 --- a/homeassistant/components/webhook/__init__.py +++ b/homeassistant/components/webhook/__init__.py @@ -178,10 +178,10 @@ async def async_handle_webhook( response: Response | None = await webhook["handler"](hass, webhook_id, request) if response is None: response = Response(status=HTTPStatus.OK) - return response except Exception: # pylint: disable=broad-except _LOGGER.exception("Error processing webhook %s", webhook_id) return Response(status=HTTPStatus.OK) + return response async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: diff --git a/homeassistant/components/wiz/__init__.py b/homeassistant/components/wiz/__init__.py index 6b1ac2a7721..79c317f178b 100644 --- a/homeassistant/components/wiz/__init__.py +++ b/homeassistant/components/wiz/__init__.py @@ -94,9 +94,9 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: if bulb.power_monitoring is not False: power: float | None = await bulb.get_power() return power - return None except WIZ_EXCEPTIONS as ex: raise UpdateFailed(f"Failed to update device at {ip_address}: {ex}") from ex + return None coordinator = DataUpdateCoordinator( hass=hass, diff --git a/homeassistant/components/xiaomi_miio/device.py b/homeassistant/components/xiaomi_miio/device.py index 2f5e6e299e9..39cb0ee5f96 100644 --- a/homeassistant/components/xiaomi_miio/device.py +++ b/homeassistant/components/xiaomi_miio/device.py @@ -150,16 +150,15 @@ class XiaomiCoordinatedMiioEntity(CoordinatorEntity[_T]): result = await self.hass.async_add_executor_job( partial(func, *args, **kwargs) ) - - _LOGGER.debug("Response received from miio device: %s", result) - - return True except DeviceException as exc: if self.available: _LOGGER.error(mask_error, exc) return False + _LOGGER.debug("Response received from miio device: %s", result) + return True + @classmethod def _extract_value_from_attribute(cls, state, attribute): value = getattr(state, attribute) diff --git a/homeassistant/components/xiaomi_miio/light.py b/homeassistant/components/xiaomi_miio/light.py index cbbf12f9ab1..96f9595e0e8 100644 --- a/homeassistant/components/xiaomi_miio/light.py +++ b/homeassistant/components/xiaomi_miio/light.py @@ -292,10 +292,6 @@ class XiaomiPhilipsAbstractLight(XiaomiMiioEntity, LightEntity): result = await self.hass.async_add_executor_job( partial(func, *args, **kwargs) ) - - _LOGGER.debug("Response received from light: %s", result) - - return result == SUCCESS except DeviceException as exc: if self._available: _LOGGER.error(mask_error, exc) @@ -303,6 +299,9 @@ class XiaomiPhilipsAbstractLight(XiaomiMiioEntity, LightEntity): return False + _LOGGER.debug("Response received from light: %s", result) + return result == SUCCESS + async def async_turn_on(self, **kwargs: Any) -> None: """Turn the light on.""" if ATTR_BRIGHTNESS in kwargs: diff --git a/homeassistant/components/xiaomi_miio/remote.py b/homeassistant/components/xiaomi_miio/remote.py index c1234b77bbc..cd3b3192520 100644 --- a/homeassistant/components/xiaomi_miio/remote.py +++ b/homeassistant/components/xiaomi_miio/remote.py @@ -225,9 +225,9 @@ class XiaomiMiioRemote(RemoteEntity): """Return False if device is unreachable, else True.""" try: self.device.info() - return True except DeviceException: return False + return True async def async_turn_on(self, **kwargs: Any) -> None: """Turn the device on.""" diff --git a/homeassistant/components/xiaomi_miio/switch.py b/homeassistant/components/xiaomi_miio/switch.py index 02517d00c57..34ebb9addf5 100644 --- a/homeassistant/components/xiaomi_miio/switch.py +++ b/homeassistant/components/xiaomi_miio/switch.py @@ -805,14 +805,6 @@ class XiaomiPlugGenericSwitch(XiaomiMiioEntity, SwitchEntity): result = await self.hass.async_add_executor_job( partial(func, *args, **kwargs) ) - - _LOGGER.debug("Response received from plug: %s", result) - - # The Chuangmi Plug V3 returns 0 on success on usb_on/usb_off. - if func in ["usb_on", "usb_off"] and result == 0: - return True - - return result == SUCCESS except DeviceException as exc: if self._available: _LOGGER.error(mask_error, exc) @@ -820,6 +812,14 @@ class XiaomiPlugGenericSwitch(XiaomiMiioEntity, SwitchEntity): return False + _LOGGER.debug("Response received from plug: %s", result) + + # The Chuangmi Plug V3 returns 0 on success on usb_on/usb_off. + if func in ["usb_on", "usb_off"] and result == 0: + return True + + return result == SUCCESS + async def async_turn_on(self, **kwargs: Any) -> None: """Turn the plug on.""" result = await self._try_command("Turning the plug on failed", self._device.on) diff --git a/homeassistant/components/xiaomi_miio/vacuum.py b/homeassistant/components/xiaomi_miio/vacuum.py index 41f2c2386e1..ef6f94c162f 100644 --- a/homeassistant/components/xiaomi_miio/vacuum.py +++ b/homeassistant/components/xiaomi_miio/vacuum.py @@ -281,10 +281,10 @@ class MiroboVacuum( try: await self.hass.async_add_executor_job(partial(func, *args, **kwargs)) await self.coordinator.async_refresh() - return True except DeviceException as exc: _LOGGER.error(mask_error, exc) return False + return True async def async_start(self) -> None: """Start or resume the cleaning task.""" diff --git a/homeassistant/components/zamg/weather.py b/homeassistant/components/zamg/weather.py index 241b2232eeb..286a6460f19 100644 --- a/homeassistant/components/zamg/weather.py +++ b/homeassistant/components/zamg/weather.py @@ -66,9 +66,9 @@ class ZamgWeather(CoordinatorEntity, WeatherEntity): value := self.coordinator.data[self.station_id]["TL"]["data"] ) is not None: return float(value) - return None except (KeyError, ValueError, TypeError): return None + return None @property def native_pressure(self) -> float | None: @@ -98,9 +98,9 @@ class ZamgWeather(CoordinatorEntity, WeatherEntity): value := self.coordinator.data[self.station_id]["FFX"]["data"] ) is not None: return float(value) - return None except (KeyError, ValueError, TypeError): return None + return None @property def wind_bearing(self) -> float | None: @@ -114,6 +114,6 @@ class ZamgWeather(CoordinatorEntity, WeatherEntity): value := self.coordinator.data[self.station_id]["DDX"]["data"] ) is not None: return float(value) - return None except (KeyError, ValueError, TypeError): return None + return None diff --git a/homeassistant/components/zha/core/device.py b/homeassistant/components/zha/core/device.py index e6d9f3e66b5..e5fdfe36a9b 100644 --- a/homeassistant/components/zha/core/device.py +++ b/homeassistant/components/zha/core/device.py @@ -789,15 +789,6 @@ class ZHADevice(LogMixin): response = await cluster.write_attributes( {attribute: value}, manufacturer=manufacturer ) - self.debug( - "set: %s for attr: %s to cluster: %s for ept: %s - res: %s", - value, - attribute, - cluster_id, - endpoint_id, - response, - ) - return response except zigpy.exceptions.ZigbeeException as exc: raise HomeAssistantError( f"Failed to set attribute: " @@ -807,6 +798,16 @@ class ZHADevice(LogMixin): f"{ATTR_ENDPOINT_ID}: {endpoint_id}" ) from exc + self.debug( + "set: %s for attr: %s to cluster: %s for ept: %s - res: %s", + value, + attribute, + cluster_id, + endpoint_id, + response, + ) + return response + async def issue_cluster_command( self, endpoint_id: int, diff --git a/homeassistant/components/zha/core/helpers.py b/homeassistant/components/zha/core/helpers.py index 1a001cab381..b060d56cb04 100644 --- a/homeassistant/components/zha/core/helpers.py +++ b/homeassistant/components/zha/core/helpers.py @@ -102,9 +102,9 @@ async def safe_read( only_cache=only_cache, manufacturer=manufacturer, ) - return result except Exception: # pylint: disable=broad-except return {} + return result async def get_matched_clusters( diff --git a/homeassistant/config.py b/homeassistant/config.py index c570e36c6c1..d3f30f84a68 100644 --- a/homeassistant/config.py +++ b/homeassistant/config.py @@ -464,14 +464,12 @@ def _write_default_config(config_dir: str) -> bool: if not os.path.isfile(scene_yaml_path): with open(scene_yaml_path, "w", encoding="utf8"): pass - - return True - except OSError: print( # noqa: T201 f"Unable to create default configuration file {config_path}" ) return False + return True async def async_hass_config_yaml(hass: HomeAssistant) -> dict: diff --git a/homeassistant/config_entries.py b/homeassistant/config_entries.py index 890db26810a..9f5f6b9135b 100644 --- a/homeassistant/config_entries.py +++ b/homeassistant/config_entries.py @@ -763,8 +763,6 @@ class ConfigEntry: self._async_set_state(hass, ConfigEntryState.NOT_LOADED, None) await self._async_process_on_unload(hass) - - return result except Exception as exc: # pylint: disable=broad-except _LOGGER.exception( "Error unloading entry %s for %s", self.title, integration.domain @@ -774,6 +772,7 @@ class ConfigEntry: hass, ConfigEntryState.FAILED_UNLOAD, str(exc) or "Unknown error" ) return False + return result async def async_remove(self, hass: HomeAssistant) -> None: """Invoke remove callback on component.""" @@ -872,12 +871,12 @@ class ConfigEntry: if result: # pylint: disable-next=protected-access hass.config_entries._async_schedule_save() - return result except Exception: # pylint: disable=broad-except _LOGGER.exception( "Error migrating entry %s for %s", self.title, self.domain ) return False + return result def add_update_listener(self, listener: UpdateListenerType) -> CALLBACK_TYPE: """Listen for when entry is updated. diff --git a/homeassistant/core.py b/homeassistant/core.py index 082c1a756c3..6a923f4ab16 100644 --- a/homeassistant/core.py +++ b/homeassistant/core.py @@ -2691,9 +2691,10 @@ class Config: for allowed_path in self.allowlist_external_dirs: try: thepath.relative_to(allowed_path) - return True except ValueError: pass + else: + return True return False diff --git a/homeassistant/helpers/config_validation.py b/homeassistant/helpers/config_validation.py index f7245607be7..fc39db83658 100644 --- a/homeassistant/helpers/config_validation.py +++ b/homeassistant/helpers/config_validation.py @@ -248,13 +248,13 @@ def is_regex(value: Any) -> re.Pattern[Any]: """Validate that a string is a valid regular expression.""" try: r = re.compile(value) - return r except TypeError as err: raise vol.Invalid( f"value {value} is of the wrong type for a regular expression" ) from err except re.error as err: raise vol.Invalid(f"value {value} is not a valid regular expression") from err + return r def isfile(value: Any) -> str: @@ -671,9 +671,9 @@ def template(value: Any | None) -> template_helper.Template: try: template_value.ensure_valid() - return template_value except TemplateError as ex: raise vol.Invalid(f"invalid template ({ex})") from ex + return template_value def dynamic_template(value: Any | None) -> template_helper.Template: @@ -693,9 +693,9 @@ def dynamic_template(value: Any | None) -> template_helper.Template: try: template_value.ensure_valid() - return template_value except TemplateError as ex: raise vol.Invalid(f"invalid template ({ex})") from ex + return template_value def template_complex(value: Any) -> Any: diff --git a/homeassistant/helpers/entity_platform.py b/homeassistant/helpers/entity_platform.py index 1cff472af72..f605f8381b0 100644 --- a/homeassistant/helpers/entity_platform.py +++ b/homeassistant/helpers/entity_platform.py @@ -362,10 +362,6 @@ class EntityPlatform: pending = self._tasks.copy() self._tasks.clear() await asyncio.gather(*pending) - - hass.config.components.add(full_name) - self._setup_complete = True - return True except PlatformNotReady as ex: tries += 1 wait_time = min(tries, 6) * PLATFORM_NOT_READY_BASE_WAIT_TIME @@ -417,6 +413,10 @@ class EntityPlatform: self.domain, ) return False + else: + hass.config.components.add(full_name) + self._setup_complete = True + return True finally: warn_task.cancel() diff --git a/homeassistant/helpers/entity_registry.py b/homeassistant/helpers/entity_registry.py index ef9274c6ceb..ad9ddcd5c4c 100644 --- a/homeassistant/helpers/entity_registry.py +++ b/homeassistant/helpers/entity_registry.py @@ -243,7 +243,6 @@ class RegistryEntry: try: dict_repr = self._as_display_dict json_repr: bytes | None = json_bytes(dict_repr) if dict_repr else None - return json_repr except (ValueError, TypeError): _LOGGER.error( "Unable to serialize entry %s to JSON. Bad data found at %s", @@ -252,8 +251,8 @@ class RegistryEntry: find_paths_unserializable_data(dict_repr, dump=JSON_DUMP) ), ) - - return None + return None + return json_repr @cached_property def as_partial_dict(self) -> dict[str, Any]: diff --git a/homeassistant/helpers/intent.py b/homeassistant/helpers/intent.py index 63214cb135b..0a9b441d99b 100644 --- a/homeassistant/helpers/intent.py +++ b/homeassistant/helpers/intent.py @@ -109,7 +109,6 @@ async def async_handle( try: _LOGGER.info("Triggering intent handler %s", handler) result = await handler.async_handle(intent) - return result except vol.Invalid as err: _LOGGER.warning("Received invalid slot info for %s: %s", intent_type, err) raise InvalidSlotInfo(f"Received invalid slot info for {intent_type}") from err @@ -117,6 +116,7 @@ async def async_handle( raise # bubble up intent related errors except Exception as err: raise IntentUnexpectedError(f"Error handling {intent_type}") from err + return result class IntentError(HomeAssistantError): diff --git a/homeassistant/helpers/network.py b/homeassistant/helpers/network.py index ed6339f9996..6e8fa8dc3a3 100644 --- a/homeassistant/helpers/network.py +++ b/homeassistant/helpers/network.py @@ -31,9 +31,9 @@ def is_internal_request(hass: HomeAssistant) -> bool: get_url( hass, allow_external=False, allow_cloud=False, require_current_request=True ) - return True except NoURLAvailableError: return False + return True @bind_hass diff --git a/homeassistant/setup.py b/homeassistant/setup.py index 178ee6425e3..32bb8f361d6 100644 --- a/homeassistant/setup.py +++ b/homeassistant/setup.py @@ -166,7 +166,6 @@ async def async_setup_component( setup_future.set_result(result) if setup_done_future := setup_done_futures.pop(domain, None): setup_done_future.set_result(result) - return result except BaseException as err: futures = [setup_future] if setup_done_future := setup_done_futures.pop(domain, None): @@ -185,6 +184,7 @@ async def async_setup_component( # if there are no concurrent setup attempts await future raise + return result async def _async_process_dependencies( diff --git a/pyproject.toml b/pyproject.toml index 891ea511ba5..80381b09825 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -714,8 +714,7 @@ ignore = [ # temporarily disabled "PT019", "TRY002", - "TRY301", - "TRY300" + "TRY301" ] [tool.ruff.lint.flake8-import-conventions.extend-aliases] diff --git a/tests/components/gardena_bluetooth/conftest.py b/tests/components/gardena_bluetooth/conftest.py index af882e35751..052de4bf311 100644 --- a/tests/components/gardena_bluetooth/conftest.py +++ b/tests/components/gardena_bluetooth/conftest.py @@ -88,11 +88,11 @@ def mock_client( val = mock_read_char_raw[uuid] if isinstance(val, Exception): raise val - return val except KeyError: if default is SENTINEL: raise CharacteristicNotFound from KeyError return default + return val def _all_char(): return set(mock_read_char_raw.keys())