Skip to content

Commit

Permalink
Enable Ruff TRY201 (home-assistant#114269)
Browse files Browse the repository at this point in the history
* Enable Ruff TRY201

* remove redundant rules
  • Loading branch information
autinerd authored Mar 28, 2024
1 parent 071c3ab commit f7b7f74
Show file tree
Hide file tree
Showing 36 changed files with 71 additions and 66 deletions.
2 changes: 1 addition & 1 deletion homeassistant/components/airthings_ble/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/aladdin_connect/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/aurora_abb_powerone/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/automation/trace.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
2 changes: 1 addition & 1 deletion homeassistant/components/deluge/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 1 addition & 1 deletion homeassistant/components/ecovacs/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/freebox/router.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ async def get_hosts_list_if_supported(
)

else:
raise err
raise

return supports_hosts, fbx_devices

Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/fronius/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/generic/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 {}


Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/google_assistant_sdk/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/google_sheets/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/http/headers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 4 additions & 4 deletions homeassistant/components/lametric/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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"
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/onkyo/media_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -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")
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/onvif/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -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],
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/onvif/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/reolink/host.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/risco/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/roborock/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/script/trace.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
6 changes: 3 additions & 3 deletions homeassistant/components/signal_messenger/notify.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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:
Expand Down Expand Up @@ -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
Expand Down
8 changes: 4 additions & 4 deletions homeassistant/components/stream/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/syncthru/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/synology_dsm/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand Down Expand Up @@ -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."""
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/tank_utility/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/tessie/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/twitch/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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,
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/voip/voip.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/wallbox/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down Expand Up @@ -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."""
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/wiz/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/helpers/condition.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading

0 comments on commit f7b7f74

Please sign in to comment.