diff --git a/homeassistant/components/airthings_ble/config_flow.py b/homeassistant/components/airthings_ble/config_flow.py index 5f08f1987619b..d525aee04b1d8 100644 --- a/homeassistant/components/airthings_ble/config_flow.py +++ b/homeassistant/components/airthings_ble/config_flow.py @@ -87,7 +87,7 @@ async def _get_device_data( _LOGGER.error( "Unknown error occurred from %s: %s", discovery_info.address, err ) - raise err + raise return data async def async_step_bluetooth( diff --git a/homeassistant/components/aladdin_connect/config_flow.py b/homeassistant/components/aladdin_connect/config_flow.py index df822086db7ce..e960138853a06 100644 --- a/homeassistant/components/aladdin_connect/config_flow.py +++ b/homeassistant/components/aladdin_connect/config_flow.py @@ -41,8 +41,8 @@ async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> None: ) try: await acc.login() - except (ClientError, TimeoutError, Aladdin.ConnectionError) as ex: - raise ex + except (ClientError, TimeoutError, Aladdin.ConnectionError): + raise except Aladdin.InvalidPasswordError as ex: raise InvalidAuth from ex diff --git a/homeassistant/components/aurora_abb_powerone/config_flow.py b/homeassistant/components/aurora_abb_powerone/config_flow.py index 3f63559525866..a1e046f302f4f 100644 --- a/homeassistant/components/aurora_abb_powerone/config_flow.py +++ b/homeassistant/components/aurora_abb_powerone/config_flow.py @@ -46,9 +46,9 @@ def validate_and_connect( ret[ATTR_MODEL] = f"{client.version()} ({client.pn()})" ret[ATTR_FIRMWARE] = client.firmware(1) _LOGGER.info("Returning device info=%s", ret) - except AuroraError as err: + except AuroraError: _LOGGER.warning("Could not connect to device=%s", comport) - raise err + raise finally: if client.serline.isOpen(): client.close() diff --git a/homeassistant/components/automation/trace.py b/homeassistant/components/automation/trace.py index 754c062ec2c8a..e7f671e6f0512 100644 --- a/homeassistant/components/automation/trace.py +++ b/homeassistant/components/automation/trace.py @@ -65,7 +65,7 @@ def trace_automation( except Exception as ex: if automation_id: trace.set_error(ex) - raise ex + raise finally: if automation_id: trace.finished() diff --git a/homeassistant/components/deluge/coordinator.py b/homeassistant/components/deluge/coordinator.py index 6b3c177b90d1e..c3dd25609fead 100644 --- a/homeassistant/components/deluge/coordinator.py +++ b/homeassistant/components/deluge/coordinator.py @@ -63,5 +63,5 @@ async def _async_update_data(self) -> dict[Platform, dict[str, Any]]: "Credentials for Deluge client are not valid" ) from ex LOGGER.error("Unknown error connecting to Deluge: %s", ex) - raise ex + raise return data diff --git a/homeassistant/components/ecovacs/config_flow.py b/homeassistant/components/ecovacs/config_flow.py index 8cf82f6237c69..a1ea19144b041 100644 --- a/homeassistant/components/ecovacs/config_flow.py +++ b/homeassistant/components/ecovacs/config_flow.py @@ -303,7 +303,7 @@ def create_repair( except AbortFlow as ex: if ex.reason == "already_configured": create_repair() - raise ex + raise if errors := result.get("errors"): error = errors["base"] diff --git a/homeassistant/components/freebox/router.py b/homeassistant/components/freebox/router.py index 26b3e37beb392..ef16a9df1b12c 100644 --- a/homeassistant/components/freebox/router.py +++ b/homeassistant/components/freebox/router.py @@ -87,7 +87,7 @@ async def get_hosts_list_if_supported( ) else: - raise err + raise return supports_hosts, fbx_devices diff --git a/homeassistant/components/fronius/coordinator.py b/homeassistant/components/fronius/coordinator.py index d0a20b25bee52..1ecd74a6e0953 100644 --- a/homeassistant/components/fronius/coordinator.py +++ b/homeassistant/components/fronius/coordinator.py @@ -152,9 +152,9 @@ async def _update_method(self) -> dict[SolarNetId, Any]: data = await self.solar_net.fronius.current_inverter_data( self.inverter_info.solar_net_id ) - except BadStatusError as err: + except BadStatusError: if silent_retry == (self.SILENT_RETRIES - 1): - raise err + raise continue break # wrap a single devices data in a dict with solar_net_id key for diff --git a/homeassistant/components/generic/config_flow.py b/homeassistant/components/generic/config_flow.py index 8fdc01437002b..af33ae3b36fe1 100644 --- a/homeassistant/components/generic/config_flow.py +++ b/homeassistant/components/generic/config_flow.py @@ -291,7 +291,7 @@ async def async_test_stream( return {CONF_STREAM_SOURCE: "stream_no_route_to_host"} if err.errno == EIO: # input/output error return {CONF_STREAM_SOURCE: "stream_io_error"} - raise err + raise return {} diff --git a/homeassistant/components/google_assistant_sdk/helpers.py b/homeassistant/components/google_assistant_sdk/helpers.py index 0c4d081961f07..ccd0fe765acdc 100644 --- a/homeassistant/components/google_assistant_sdk/helpers.py +++ b/homeassistant/components/google_assistant_sdk/helpers.py @@ -70,7 +70,7 @@ async def async_send_text_commands( except aiohttp.ClientResponseError as err: if 400 <= err.status < 500: entry.async_start_reauth(hass) - raise err + raise credentials = Credentials(session.token[CONF_ACCESS_TOKEN]) language_code = entry.options.get(CONF_LANGUAGE_CODE, default_language_code(hass)) diff --git a/homeassistant/components/google_sheets/__init__.py b/homeassistant/components/google_sheets/__init__.py index bf7cf7c40df9d..f346f913e0c83 100644 --- a/homeassistant/components/google_sheets/__init__.py +++ b/homeassistant/components/google_sheets/__init__.py @@ -96,9 +96,9 @@ def _append_to_sheet(call: ServiceCall, entry: ConfigEntry) -> None: service = Client(Credentials(entry.data[CONF_TOKEN][CONF_ACCESS_TOKEN])) try: sheet = service.open_by_key(entry.unique_id) - except RefreshError as ex: + except RefreshError: entry.async_start_reauth(hass) - raise ex + raise except APIError as ex: raise HomeAssistantError("Failed to write data") from ex diff --git a/homeassistant/components/http/headers.py b/homeassistant/components/http/headers.py index bd05401ebce26..3c845601183b9 100644 --- a/homeassistant/components/http/headers.py +++ b/homeassistant/components/http/headers.py @@ -33,7 +33,7 @@ async def headers_middleware( except HTTPException as err: for key, value in added_headers.items(): err.headers[key] = value - raise err + raise for key, value in added_headers.items(): response.headers[key] = value diff --git a/homeassistant/components/lametric/config_flow.py b/homeassistant/components/lametric/config_flow.py index ed1477e1149b2..f21b0cb0a3c25 100644 --- a/homeassistant/components/lametric/config_flow.py +++ b/homeassistant/components/lametric/config_flow.py @@ -147,8 +147,8 @@ async def async_step_manual_entry( return await self._async_step_create_entry( host, user_input[CONF_API_KEY] ) - except AbortFlow as ex: - raise ex + except AbortFlow: + raise except LaMetricConnectionError as ex: LOGGER.error("Error connecting to LaMetric: %s", ex) errors["base"] = "cannot_connect" @@ -209,8 +209,8 @@ async def async_step_cloud_select_device( return await self._async_step_create_entry( str(device.ip), device.api_key ) - except AbortFlow as ex: - raise ex + except AbortFlow: + raise except LaMetricConnectionError as ex: LOGGER.error("Error connecting to LaMetric: %s", ex) errors["base"] = "cannot_connect" diff --git a/homeassistant/components/onkyo/media_player.py b/homeassistant/components/onkyo/media_player.py index ef0105bd6d240..c0503e6e850f5 100644 --- a/homeassistant/components/onkyo/media_player.py +++ b/homeassistant/components/onkyo/media_player.py @@ -143,7 +143,7 @@ def determine_zones(receiver): _LOGGER.debug("Zone 2 not available") except ValueError as error: if str(error) != TIMEOUT_MESSAGE: - raise error + raise _LOGGER.debug("Zone 2 timed out, assuming no functionality") try: _LOGGER.debug("Checking for zone 3 capability") @@ -154,7 +154,7 @@ def determine_zones(receiver): _LOGGER.debug("Zone 3 not available") except ValueError as error: if str(error) != TIMEOUT_MESSAGE: - raise error + raise _LOGGER.debug("Zone 3 timed out, assuming no functionality") except AssertionError: _LOGGER.error("Zone 3 detection failed") diff --git a/homeassistant/components/onvif/config_flow.py b/homeassistant/components/onvif/config_flow.py index 515f9cd5f689c..5bd81f2bdeaa6 100644 --- a/homeassistant/components/onvif/config_flow.py +++ b/homeassistant/components/onvif/config_flow.py @@ -311,7 +311,7 @@ async def async_setup_profiles( self.device_id = interface.Info.HwAddress except Fault as fault: if "not implemented" not in fault.message: - raise fault + raise LOGGER.debug( "%s: Could not get network interfaces: %s", self.onvif_config[CONF_NAME], diff --git a/homeassistant/components/onvif/device.py b/homeassistant/components/onvif/device.py index 2001d95e2d453..71acf62f97d37 100644 --- a/homeassistant/components/onvif/device.py +++ b/homeassistant/components/onvif/device.py @@ -344,7 +344,7 @@ async def async_get_device_info(self) -> DeviceInfo: mac = interface.Info.HwAddress except Fault as fault: if "not implemented" not in fault.message: - raise fault + raise LOGGER.debug( "Couldn't get network interfaces from ONVIF device '%s'. Error: %s", diff --git a/homeassistant/components/reolink/host.py b/homeassistant/components/reolink/host.py index 44750cdeb3c9a..73e6ddd611531 100644 --- a/homeassistant/components/reolink/host.py +++ b/homeassistant/components/reolink/host.py @@ -351,7 +351,7 @@ async def _async_start_long_polling(self, initial=False) -> None: await self._api.subscribe(sub_type=SubType.long_poll) except NotSupportedError as err: if initial: - raise err + raise # make sure the long_poll_task is always created to try again later if not self._lost_subscription: self._lost_subscription = True @@ -552,7 +552,7 @@ async def _async_long_polling(self, *_) -> None: "Unexpected exception while requesting ONVIF pull point: %s", ex ) await self._api.unsubscribe(sub_type=SubType.long_poll) - raise ex + raise self._long_poll_error = False diff --git a/homeassistant/components/risco/config_flow.py b/homeassistant/components/risco/config_flow.py index 0f13721856c5f..ab372be3a1413 100644 --- a/homeassistant/components/risco/config_flow.py +++ b/homeassistant/components/risco/config_flow.py @@ -103,9 +103,9 @@ async def validate_local_input( ) try: await risco.connect() - except CannotConnectError as e: + except CannotConnectError: if comm_delay >= MAX_COMMUNICATION_DELAY: - raise e + raise comm_delay += 1 else: break diff --git a/homeassistant/components/roborock/__init__.py b/homeassistant/components/roborock/__init__.py index c01d1fc7c9b41..e64b83be1ddad 100644 --- a/homeassistant/components/roborock/__init__.py +++ b/homeassistant/components/roborock/__init__.py @@ -115,7 +115,7 @@ async def setup_device( ) _LOGGER.debug(err) await mqtt_client.async_release() - raise err + raise coordinator = RoborockDataUpdateCoordinator( hass, device, networking, product_info, mqtt_client ) diff --git a/homeassistant/components/script/trace.py b/homeassistant/components/script/trace.py index a50cda752d0a5..0013f1411ddb4 100644 --- a/homeassistant/components/script/trace.py +++ b/homeassistant/components/script/trace.py @@ -40,7 +40,7 @@ def trace_script( except Exception as ex: if item_id: trace.set_error(ex) - raise ex + raise finally: if item_id: trace.finished() diff --git a/homeassistant/components/signal_messenger/notify.py b/homeassistant/components/signal_messenger/notify.py index 58cd85fb26e87..9c8846b27671a 100644 --- a/homeassistant/components/signal_messenger/notify.py +++ b/homeassistant/components/signal_messenger/notify.py @@ -94,7 +94,7 @@ def send_message(self, message: str = "", **kwargs: Any) -> None: data = DATA_SCHEMA(data) except vol.Invalid as ex: _LOGGER.error("Invalid message data: %s", ex) - raise ex + raise filenames = self.get_filenames(data) attachments_as_bytes = self.get_attachments_as_bytes( @@ -107,7 +107,7 @@ def send_message(self, message: str = "", **kwargs: Any) -> None: ) except SignalCliRestApiError as ex: _LOGGER.error("%s", ex) - raise ex + raise @staticmethod def get_filenames(data: Any) -> list[str] | None: @@ -174,7 +174,7 @@ def get_attachments_as_bytes( attachments_as_bytes.append(chunks) except Exception as ex: _LOGGER.error("%s", ex) - raise ex + raise if not attachments_as_bytes: return None diff --git a/homeassistant/components/stream/worker.py b/homeassistant/components/stream/worker.py index 87d9118f3a524..670d6b93c0e39 100644 --- a/homeassistant/components/stream/worker.py +++ b/homeassistant/components/stream/worker.py @@ -583,9 +583,9 @@ def is_video(packet: av.Packet) -> Any: # dts. Use "or 1" to deal with this. start_dts = next_video_packet.dts - (next_video_packet.duration or 1) first_keyframe.dts = first_keyframe.pts = start_dts - except StreamWorkerError as ex: + except StreamWorkerError: container.close() - raise ex + raise except StopIteration as ex: container.close() raise StreamEndedError("Stream ended; no additional packets") from ex @@ -612,8 +612,8 @@ def is_video(packet: av.Packet) -> Any: while not quit_event.is_set(): try: packet = next(container_packets) - except StreamWorkerError as ex: - raise ex + except StreamWorkerError: + raise except StopIteration as ex: raise StreamEndedError("Stream ended; no additional packets") from ex except av.AVError as ex: diff --git a/homeassistant/components/syncthru/__init__.py b/homeassistant/components/syncthru/__init__.py index 5ad4a85cc092f..c6764de51a778 100644 --- a/homeassistant/components/syncthru/__init__.py +++ b/homeassistant/components/syncthru/__init__.py @@ -42,7 +42,7 @@ async def async_update_data() -> SyncThru: printer.url, exc_info=api_error, ) - raise api_error + raise # if the printer is offline, we raise an UpdateFailed if printer.is_unknown_state(): diff --git a/homeassistant/components/synology_dsm/common.py b/homeassistant/components/synology_dsm/common.py index 4bb523831486a..d8a2f1ede6287 100644 --- a/homeassistant/components/synology_dsm/common.py +++ b/homeassistant/components/synology_dsm/common.py @@ -129,7 +129,7 @@ async def async_setup(self) -> None: self._entry.unique_id, err, ) - raise err + raise @callback def subscribe(self, api_key: str, unique_id: str) -> Callable[[], None]: @@ -268,7 +268,7 @@ async def _syno_api_executer(self, api_call: Callable) -> None: LOGGER.debug( "Error from '%s': %s", self._entry.unique_id, err, exc_info=True ) - raise err + raise async def async_reboot(self) -> None: """Reboot NAS.""" diff --git a/homeassistant/components/tank_utility/sensor.py b/homeassistant/components/tank_utility/sensor.py index e0b3376ca2ede..b4d972f7c068e 100644 --- a/homeassistant/components/tank_utility/sensor.py +++ b/homeassistant/components/tank_utility/sensor.py @@ -126,7 +126,7 @@ def get_data(self): self._token = auth.get_token(self._email, self._password, force=True) data = tank_monitor.get_device_data(self._token, self.device) else: - raise http_error + raise data.update(data.pop("device", {})) data.update(data.pop("lastReading", {})) return data diff --git a/homeassistant/components/tessie/coordinator.py b/homeassistant/components/tessie/coordinator.py index 19d2d2c4869ff..bea1bf72a8de4 100644 --- a/homeassistant/components/tessie/coordinator.py +++ b/homeassistant/components/tessie/coordinator.py @@ -66,7 +66,7 @@ async def _async_update_data(self) -> dict[str, Any]: if e.status == HTTPStatus.UNAUTHORIZED: # Auth Token is no longer valid raise ConfigEntryAuthFailed from e - raise e + raise return self._flatten(vehicle) diff --git a/homeassistant/components/twitch/config_flow.py b/homeassistant/components/twitch/config_flow.py index f9e121f3a172a..186d097a22bb2 100644 --- a/homeassistant/components/twitch/config_flow.py +++ b/homeassistant/components/twitch/config_flow.py @@ -154,7 +154,7 @@ async def async_step_import(self, config: dict[str, Any]) -> ConfigFlowResult: await self.async_set_unique_id(user.id) try: self._abort_if_unique_id_configured() - except AbortFlow as err: + except AbortFlow: async_create_issue( self.hass, DOMAIN, @@ -168,7 +168,7 @@ async def async_step_import(self, config: dict[str, Any]) -> ConfigFlowResult: "integration_title": "Twitch", }, ) - raise err + raise async_create_issue( self.hass, HOMEASSISTANT_DOMAIN, diff --git a/homeassistant/components/voip/voip.py b/homeassistant/components/voip/voip.py index 4d97720934ce3..5770d9d2b4a2d 100644 --- a/homeassistant/components/voip/voip.py +++ b/homeassistant/components/voip/voip.py @@ -445,9 +445,9 @@ async def _send_tts(self, media_id: str) -> None: async with asyncio.timeout(tts_seconds + self.tts_extra_timeout): # TTS audio is 16Khz 16-bit mono await self._async_send_audio(audio_bytes) - except TimeoutError as err: + except TimeoutError: _LOGGER.warning("TTS timeout") - raise err + raise finally: # Signal pipeline to restart self._tts_done.set() diff --git a/homeassistant/components/wallbox/coordinator.py b/homeassistant/components/wallbox/coordinator.py index 4725e92ca8435..bf7c6d1f654d5 100644 --- a/homeassistant/components/wallbox/coordinator.py +++ b/homeassistant/components/wallbox/coordinator.py @@ -154,7 +154,7 @@ def _set_charging_current(self, charging_current: float) -> None: except requests.exceptions.HTTPError as wallbox_connection_error: if wallbox_connection_error.response.status_code == 403: raise InvalidAuth from wallbox_connection_error - raise wallbox_connection_error + raise async def async_set_charging_current(self, charging_current: float) -> None: """Set maximum charging current for Wallbox.""" @@ -185,7 +185,7 @@ def _set_lock_unlock(self, lock: bool) -> None: except requests.exceptions.HTTPError as wallbox_connection_error: if wallbox_connection_error.response.status_code == 403: raise InvalidAuth from wallbox_connection_error - raise wallbox_connection_error + raise async def async_set_lock_unlock(self, lock: bool) -> None: """Set wallbox to locked or unlocked.""" diff --git a/homeassistant/components/wiz/__init__.py b/homeassistant/components/wiz/__init__.py index 130cc73efd340..6b1ac2a77213b 100644 --- a/homeassistant/components/wiz/__init__.py +++ b/homeassistant/components/wiz/__init__.py @@ -113,9 +113,9 @@ async def _async_update() -> float | None: try: await coordinator.async_config_entry_first_refresh() - except ConfigEntryNotReady as err: + except ConfigEntryNotReady: await bulb.async_close() - raise err + raise async def _async_shutdown_on_stop(event: Event) -> None: await bulb.async_close() diff --git a/homeassistant/helpers/condition.py b/homeassistant/helpers/condition.py index e906148efdbe9..b8c85902f7f4a 100644 --- a/homeassistant/helpers/condition.py +++ b/homeassistant/helpers/condition.py @@ -164,7 +164,7 @@ def trace_condition(variables: TemplateVarsType) -> Generator[TraceElement, None yield trace_element except Exception as ex: trace_element.set_error(ex) - raise ex + raise finally: if should_pop: trace_stack_pop(trace_stack_cv) diff --git a/homeassistant/helpers/script.py b/homeassistant/helpers/script.py index a86df259f1155..2ea7b25987205 100644 --- a/homeassistant/helpers/script.py +++ b/homeassistant/helpers/script.py @@ -240,16 +240,16 @@ def async_continue_stop( yield trace_element except _AbortScript as ex: trace_element.set_error(ex.__cause__ or ex) - raise ex - except _ConditionFail as ex: + raise + except _ConditionFail: # Clear errors which may have been set when evaluating the condition trace_element.set_error(None) - raise ex - except _StopScript as ex: - raise ex + raise + except _StopScript: + raise except Exception as ex: trace_element.set_error(ex) - raise ex + raise finally: trace_stack_pop(trace_stack_cv) @@ -469,7 +469,7 @@ async def async_run(self) -> ScriptRunResult | None: if not self._script.top_level: # We already consumed the response, do not pass it on err.response = None - raise err + raise except Exception: script_execution_set("error") raise diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index a48f0133e8494..f51cda6927f34 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -2559,9 +2559,9 @@ def _log_message(self) -> None: def _fail_with_undefined_error(self, *args, **kwargs): try: return super()._fail_with_undefined_error(*args, **kwargs) - except self._undefined_exception as ex: + except self._undefined_exception: _log_fn(logging.ERROR, self._undefined_message) - raise ex + raise def __str__(self) -> str: """Log undefined __str___.""" diff --git a/homeassistant/helpers/update_coordinator.py b/homeassistant/helpers/update_coordinator.py index 287e69f7085d6..c52be9982c588 100644 --- a/homeassistant/helpers/update_coordinator.py +++ b/homeassistant/helpers/update_coordinator.py @@ -378,7 +378,7 @@ async def _async_refresh( # noqa: C901 self.config_entry.async_start_reauth(self.hass) except NotImplementedError as err: self.last_exception = err - raise err + raise except Exception as err: # pylint: disable=broad-except self.last_exception = err diff --git a/pyproject.toml b/pyproject.toml index a11ab82452bd8..b7d2cc1c9d5b3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -672,8 +672,7 @@ select = [ "T100", # Trace found: {name} used "T20", # flake8-print "TID251", # Banned imports - "TRY004", # Prefer TypeError exception for invalid type - "TRY302", # Remove exception handler; error is immediately re-raised + "TRY", # tryceratops "UP", # pyupgrade "W", # pycodestyle ] @@ -701,6 +700,8 @@ ignore = [ "SIM102", # Use a single if statement instead of nested if statements "SIM108", # Use ternary operator {contents} instead of if-else-block "SIM115", # Use context handler for opening files + "TRY003", # Avoid specifying long messages outside the exception class + "TRY400", # Use `logging.exception` instead of `logging.error` "UP006", # keep type annotation style as is "UP007", # keep type annotation style as is # Ignored due to performance: https://github.com/charliermarsh/ruff/issues/2923 @@ -724,7 +725,11 @@ ignore = [ "PLE0605", # temporarily disabled - "PT019" + "PT019", + "TRY002", + "TRY301", + "TRY300", + "TRY401" ] [tool.ruff.lint.flake8-import-conventions.extend-aliases] diff --git a/script/lint_and_test.py b/script/lint_and_test.py index 0b0562a0a8403..393c5961c7ab6 100755 --- a/script/lint_and_test.py +++ b/script/lint_and_test.py @@ -76,9 +76,9 @@ async def async_exec(*args, display=False): if display: kwargs["stderr"] = asyncio.subprocess.PIPE proc = await asyncio.create_subprocess_exec(*args, **kwargs) - except FileNotFoundError as err: + except FileNotFoundError: printc(FAIL, f"Could not execute {args[0]}. Did you install test requirements?") - raise err + raise if not display: # Readin stdout into log