1
0
mirror of https://github.com/home-assistant/core.git synced 2026-05-08 09:38:58 +01:00

Cleanup unnecessary brackets for except statements (core) (#162410)

This commit is contained in:
epenet
2026-02-06 13:45:59 +01:00
committed by GitHub
parent 3b40bb7d28
commit 1c59d846e3
19 changed files with 73 additions and 73 deletions
+2 -2
View File
@@ -385,7 +385,7 @@ def _get_by_path(data: dict | list, items: list[Hashable]) -> Any:
"""
try:
return reduce(operator.getitem, items, data) # type: ignore[arg-type]
except (KeyError, IndexError, TypeError):
except KeyError, IndexError, TypeError:
return None
@@ -604,7 +604,7 @@ def _identify_config_schema(module: ComponentProtocol) -> str | None:
try:
key = next(k for k in schema if k == module.DOMAIN)
except (TypeError, AttributeError, StopIteration):
except TypeError, AttributeError, StopIteration:
return None
except Exception:
_LOGGER.exception("Unexpected error identifying config schema")
+1 -1
View File
@@ -858,7 +858,7 @@ class ConfigEntry[_DataT = Any]:
)
# pylint: disable-next=broad-except
except (SystemExit, Exception):
except SystemExit, Exception:
_LOGGER.exception(
"Error setting up entry %s for %s", self.title, integration.domain
)
+1 -1
View File
@@ -1697,7 +1697,7 @@ class EventBus:
# delete event_type list if empty
if not self._listeners[event_type] and event_type != MATCH_ALL:
self._listeners.pop(event_type)
except (KeyError, ValueError):
except KeyError, ValueError:
# KeyError is key event_type listener did not exist
# ValueError if listener did not exist within event_type
_LOGGER.exception(
+1 -1
View File
@@ -665,7 +665,7 @@ class Config:
thepath = thepath.resolve()
else:
thepath = thepath.parent.resolve()
except (FileNotFoundError, RuntimeError, PermissionError):
except FileNotFoundError, RuntimeError, PermissionError:
return False
for allowed_path in self.allowlist_external_dirs:
@@ -235,7 +235,7 @@ class LocalOAuth2Implementation(AbstractOAuth2Implementation):
if resp.status >= 400:
try:
error_response = await resp.json()
except (ClientError, JSONDecodeError):
except ClientError, JSONDecodeError:
error_response = {}
error_code = error_response.get("error", "unknown")
error_description = error_response.get("error_description", "unknown error")
+1 -1
View File
@@ -396,7 +396,7 @@ class DeviceEntry:
try:
dict_repr = self.dict_repr
return json_bytes(dict_repr)
except (ValueError, TypeError):
except ValueError, TypeError:
_LOGGER.error(
"Unable to serialize entry %s to JSON. Bad data found at %s",
self.id,
+1 -1
View File
@@ -81,7 +81,7 @@ def _async_remove_dispatcher[*_Ts](
# to prevent memory leaks
if not signal_dispatchers:
del dispatchers[signal]
except (KeyError, ValueError):
except KeyError, ValueError:
# KeyError is key target listener did not exist
# ValueError if listener did not exist within signal
_LOGGER.warning("Unable to remove unknown dispatcher %s", target)
+3 -3
View File
@@ -271,7 +271,7 @@ class RegistryEntry:
try:
dict_repr = self._as_display_dict
json_repr: bytes | None = json_bytes(dict_repr) if dict_repr else None
except (ValueError, TypeError):
except ValueError, TypeError:
_LOGGER.error(
"Unable to serialize entry %s to JSON. Bad data found at %s",
self.entity_id,
@@ -333,7 +333,7 @@ class RegistryEntry:
try:
dict_repr = self.as_partial_dict
return json_bytes(dict_repr)
except (ValueError, TypeError):
except ValueError, TypeError:
_LOGGER.error(
"Unable to serialize entry %s to JSON. Bad data found at %s",
self.entity_id,
@@ -1775,7 +1775,7 @@ class EntityRegistry(BaseRegistry):
report_non_string_unique_id=False,
unique_id=entity["unique_id"],
)
except (TypeError, ValueError):
except TypeError, ValueError:
continue
key = (
split_entity_id(entity["entity_id"])[0],
+1 -1
View File
@@ -233,7 +233,7 @@ def find_paths_unserializable_data(
try:
dump(obj)
continue
except (ValueError, TypeError):
except ValueError, TypeError:
pass
# We convert objects with as_dict to their dict values
+1 -1
View File
@@ -502,7 +502,7 @@ class ChooseSelector(Selector[ChooseSelectorConfig]):
for choice in self.config["choices"].values():
try:
validated = selector(choice["selector"])(data) # type: ignore[operator]
except (vol.Invalid, vol.MultipleInvalid):
except vol.Invalid, vol.MultipleInvalid:
continue
else:
return validated
+1 -1
View File
@@ -81,7 +81,7 @@ async def async_get_system_info(hass: HomeAssistant) -> dict[str, Any]:
try:
info_object["user"] = cached_get_user()
except (KeyError, OSError):
except KeyError, OSError:
# OSError on python >= 3.13, KeyError on python < 3.13
# KeyError can be removed when 3.12 support is dropped
# see https://docs.python.org/3/whatsnew/3.13.html
+7 -7
View File
@@ -478,7 +478,7 @@ class Template:
"""Parse the result."""
try:
return _cached_parse_result(render_result)
except (ValueError, TypeError, SyntaxError, MemoryError):
except ValueError, TypeError, SyntaxError, MemoryError:
pass
return render_result
@@ -1416,7 +1416,7 @@ def forgiving_round(value, precision=0, method="common", default=_SENTINEL):
# if method is common or something else, use common rounding
value = round(float(value), precision)
return int(value) if precision == 0 else value
except (ValueError, TypeError):
except ValueError, TypeError:
# If value can't be converted to float
if default is _SENTINEL:
raise_no_default("round", value)
@@ -1427,7 +1427,7 @@ def multiply(value, amount, default=_SENTINEL):
"""Filter to convert value to float and multiply it."""
try:
return float(value) * amount
except (ValueError, TypeError):
except ValueError, TypeError:
# If value can't be converted to float
if default is _SENTINEL:
raise_no_default("multiply", value)
@@ -1438,7 +1438,7 @@ def add(value, amount, default=_SENTINEL):
"""Filter to convert value to float and add it."""
try:
return float(value) + amount
except (ValueError, TypeError):
except ValueError, TypeError:
# If value can't be converted to float
if default is _SENTINEL:
raise_no_default("add", value)
@@ -1546,7 +1546,7 @@ def forgiving_float(value, default=_SENTINEL):
"""Try to convert value to a float."""
try:
return float(value)
except (ValueError, TypeError):
except ValueError, TypeError:
if default is _SENTINEL:
raise_no_default("float", value)
return default
@@ -1556,7 +1556,7 @@ def forgiving_float_filter(value, default=_SENTINEL):
"""Try to convert value to a float."""
try:
return float(value)
except (ValueError, TypeError):
except ValueError, TypeError:
if default is _SENTINEL:
raise_no_default("float", value)
return default
@@ -1582,7 +1582,7 @@ def is_number(value):
"""Try to convert value to a float."""
try:
fvalue = float(value)
except (ValueError, TypeError):
except ValueError, TypeError:
return False
if not math.isfinite(fvalue):
return False
@@ -145,7 +145,7 @@ class DateTimeExtension(BaseTemplateExtension):
result = dt_util.as_local(result)
return result.strftime(date_format)
except (ValueError, TypeError):
except ValueError, TypeError:
# If timestamp can't be converted
if default is _SENTINEL:
raise_no_default("timestamp_custom", value)
@@ -155,7 +155,7 @@ class DateTimeExtension(BaseTemplateExtension):
"""Filter to convert given timestamp to local date/time."""
try:
return dt_util.as_local(dt_util.utc_from_timestamp(value)).isoformat()
except (ValueError, TypeError):
except ValueError, TypeError:
# If timestamp can't be converted
if default is _SENTINEL:
raise_no_default("timestamp_local", value)
@@ -165,7 +165,7 @@ class DateTimeExtension(BaseTemplateExtension):
"""Filter to convert given timestamp to UTC date/time."""
try:
return dt_util.utc_from_timestamp(value).isoformat()
except (ValueError, TypeError):
except ValueError, TypeError:
# If timestamp can't be converted
if default is _SENTINEL:
raise_no_default("timestamp_utc", value)
@@ -175,7 +175,7 @@ class DateTimeExtension(BaseTemplateExtension):
"""Filter and function which tries to convert value to timestamp."""
try:
return dt_util.as_timestamp(value)
except (ValueError, TypeError):
except ValueError, TypeError:
if default is _SENTINEL:
raise_no_default("as_timestamp", value)
return default
@@ -192,11 +192,11 @@ class DateTimeExtension(BaseTemplateExtension):
# Check for a valid UNIX timestamp string, int or float
timestamp = float(value)
return dt_util.utc_from_timestamp(timestamp)
except (ValueError, TypeError):
except ValueError, TypeError:
# Try to parse datetime string to datetime object
try:
return dt_util.parse_datetime(value, raise_on_error=True)
except (ValueError, TypeError):
except ValueError, TypeError:
if default is _SENTINEL:
# Return None on string input
# to ensure backwards compatibility with HA Core 2024.1 and before.
@@ -213,7 +213,7 @@ class DateTimeExtension(BaseTemplateExtension):
"""Parse a time string to datetime."""
try:
return datetime.strptime(string, fmt)
except (ValueError, AttributeError, TypeError):
except ValueError, AttributeError, TypeError:
if default is _SENTINEL:
raise_no_default("strptime", string)
return default
@@ -89,14 +89,14 @@ class MathExtension(BaseTemplateExtension):
"""Filter and function to get logarithm of the value with a specific base."""
try:
base_float = float(base)
except (ValueError, TypeError):
except ValueError, TypeError:
if default is _SENTINEL:
raise_no_default("log", base)
return default
try:
value_float = float(value)
return math.log(value_float, base_float)
except (ValueError, TypeError):
except ValueError, TypeError:
if default is _SENTINEL:
raise_no_default("log", value)
return default
@@ -106,7 +106,7 @@ class MathExtension(BaseTemplateExtension):
"""Filter and function to get sine of the value."""
try:
return math.sin(float(value))
except (ValueError, TypeError):
except ValueError, TypeError:
if default is _SENTINEL:
raise_no_default("sin", value)
return default
@@ -116,7 +116,7 @@ class MathExtension(BaseTemplateExtension):
"""Filter and function to get cosine of the value."""
try:
return math.cos(float(value))
except (ValueError, TypeError):
except ValueError, TypeError:
if default is _SENTINEL:
raise_no_default("cos", value)
return default
@@ -126,7 +126,7 @@ class MathExtension(BaseTemplateExtension):
"""Filter and function to get tangent of the value."""
try:
return math.tan(float(value))
except (ValueError, TypeError):
except ValueError, TypeError:
if default is _SENTINEL:
raise_no_default("tan", value)
return default
@@ -136,7 +136,7 @@ class MathExtension(BaseTemplateExtension):
"""Filter and function to get arc sine of the value."""
try:
return math.asin(float(value))
except (ValueError, TypeError):
except ValueError, TypeError:
if default is _SENTINEL:
raise_no_default("asin", value)
return default
@@ -146,7 +146,7 @@ class MathExtension(BaseTemplateExtension):
"""Filter and function to get arc cosine of the value."""
try:
return math.acos(float(value))
except (ValueError, TypeError):
except ValueError, TypeError:
if default is _SENTINEL:
raise_no_default("acos", value)
return default
@@ -156,7 +156,7 @@ class MathExtension(BaseTemplateExtension):
"""Filter and function to get arc tangent of the value."""
try:
return math.atan(float(value))
except (ValueError, TypeError):
except ValueError, TypeError:
if default is _SENTINEL:
raise_no_default("atan", value)
return default
@@ -179,7 +179,7 @@ class MathExtension(BaseTemplateExtension):
default = args[2]
return math.atan2(float(args[0]), float(args[1]))
except (ValueError, TypeError):
except ValueError, TypeError:
if default is _SENTINEL:
raise_no_default("atan2", args)
return default
@@ -189,7 +189,7 @@ class MathExtension(BaseTemplateExtension):
"""Filter and function to get square root of the value."""
try:
return math.sqrt(float(value))
except (ValueError, TypeError):
except ValueError, TypeError:
if default is _SENTINEL:
raise_no_default("sqrt", value)
return default
@@ -218,7 +218,7 @@ class MathExtension(BaseTemplateExtension):
try:
return statistics.fmean(average_list)
except (TypeError, statistics.StatisticsError):
except TypeError, statistics.StatisticsError:
if default is _SENTINEL:
raise_no_default("average", args)
return default
@@ -247,7 +247,7 @@ class MathExtension(BaseTemplateExtension):
try:
return statistics.median(median_list)
except (TypeError, statistics.StatisticsError):
except TypeError, statistics.StatisticsError:
if default is _SENTINEL:
raise_no_default("median", args)
return default
@@ -278,7 +278,7 @@ class MathExtension(BaseTemplateExtension):
try:
return statistics.mode(mode_list)
except (TypeError, statistics.StatisticsError):
except TypeError, statistics.StatisticsError:
if default is _SENTINEL:
raise_no_default("statistical_mode", args)
return default
+3 -3
View File
@@ -593,7 +593,7 @@ def _get_numerical_value(
return None
try:
return float(state.state)
except (TypeError, ValueError):
except TypeError, ValueError:
# Entity state is not a valid number
return None
return entity_or_float
@@ -633,7 +633,7 @@ class EntityNumericalStateAttributeChangedTriggerBase(EntityTriggerBase):
try:
current_value = self._converter(_attribute_value)
except (TypeError, ValueError):
except TypeError, ValueError:
# Attribute is not a valid number, don't trigger
return False
@@ -760,7 +760,7 @@ class EntityNumericalStateAttributeCrossedThresholdTriggerBase(EntityTriggerBase
try:
current_value = self._converter(_attribute_value)
except (TypeError, ValueError):
except TypeError, ValueError:
# Attribute is not a valid number, don't trigger
return False
+1 -1
View File
@@ -64,7 +64,7 @@ def convert[_T, _U](
"""Convert value to to_type, returns default if fails."""
try:
return default if value is None else to_type(value)
except (ValueError, TypeError):
except ValueError, TypeError:
# If value could not be converted
return default
+2 -2
View File
@@ -166,12 +166,12 @@ async def _get_whoami(session: aiohttp.ClientSession) -> dict[str, Any] | None:
WHOAMI_URL_DEV if HA_VERSION.endswith("0.dev0") else WHOAMI_URL,
timeout=aiohttp.ClientTimeout(total=30),
)
except (aiohttp.ClientError, TimeoutError):
except aiohttp.ClientError, TimeoutError:
return None
try:
raw_info = await resp.json()
except (aiohttp.ClientError, ValueError):
except aiohttp.ClientError, ValueError:
return None
return {
+1 -1
View File
@@ -32,7 +32,7 @@ if __name__ == "__main__":
print()
print(f"Fatal Error: {err.reason}")
sys.exit(err.exit_code)
except (KeyboardInterrupt, EOFError):
except KeyboardInterrupt, EOFError:
print()
print("Aborted!")
sys.exit(2)
+25 -25
View File
@@ -716,7 +716,7 @@ async def test_delay_basic(hass: HomeAssistant) -> None:
assert script_obj.is_running
assert script_obj.last_action == delay_alias
except (AssertionError, TimeoutError):
except AssertionError, TimeoutError:
await script_obj.async_stop()
raise
else:
@@ -743,7 +743,7 @@ async def test_empty_delay(hass: HomeAssistant) -> None:
try:
await script_obj.async_run(context=Context())
await asyncio.wait_for(delay_started_flag.wait(), 1)
except (AssertionError, TimeoutError):
except AssertionError, TimeoutError:
await script_obj.async_stop()
raise
else:
@@ -782,7 +782,7 @@ async def test_multiple_runs_delay(hass: HomeAssistant) -> None:
assert script_obj.is_running
assert len(events) == 1
assert events[-1].data["value"] == 1
except (AssertionError, TimeoutError):
except AssertionError, TimeoutError:
await script_obj.async_stop()
raise
else:
@@ -812,7 +812,7 @@ async def test_delay_template_ok(hass: HomeAssistant) -> None:
await asyncio.wait_for(delay_started_flag.wait(), 1)
assert script_obj.is_running
except (AssertionError, TimeoutError):
except AssertionError, TimeoutError:
await script_obj.async_stop()
raise
else:
@@ -879,7 +879,7 @@ async def test_delay_template_complex_ok(hass: HomeAssistant) -> None:
hass.async_create_task(script_obj.async_run(context=Context()))
await asyncio.wait_for(delay_started_flag.wait(), 1)
assert script_obj.is_running
except (AssertionError, TimeoutError):
except AssertionError, TimeoutError:
await script_obj.async_stop()
raise
else:
@@ -946,7 +946,7 @@ async def test_cancel_delay(hass: HomeAssistant) -> None:
assert script_obj.is_running
assert len(events) == 0
except (AssertionError, TimeoutError):
except AssertionError, TimeoutError:
await script_obj.async_stop()
raise
else:
@@ -995,7 +995,7 @@ async def test_wait_basic(hass: HomeAssistant, action_type) -> None:
assert script_obj.is_running
assert script_obj.last_action == wait_alias
except (AssertionError, TimeoutError):
except AssertionError, TimeoutError:
await script_obj.async_stop()
raise
else:
@@ -1064,7 +1064,7 @@ async def test_wait_for_trigger_variables(hass: HomeAssistant) -> None:
assert script_obj.last_action == wait_alias
hass.states.async_set("switch.test", "off")
await hass.async_block_till_done()
except (AssertionError, TimeoutError):
except AssertionError, TimeoutError:
await script_obj.async_stop()
raise
else:
@@ -1167,7 +1167,7 @@ async def test_multiple_runs_wait(hass: HomeAssistant, action_type) -> None:
hass.async_create_task(script_obj.async_run())
await asyncio.wait_for(wait_started_flag.wait(), 1)
await asyncio.sleep(0)
except (AssertionError, TimeoutError):
except AssertionError, TimeoutError:
await script_obj.async_stop()
raise
else:
@@ -1208,7 +1208,7 @@ async def test_cancel_wait(hass: HomeAssistant, action_type) -> None:
assert script_obj.is_running
assert len(events) == 0
except (AssertionError, TimeoutError):
except AssertionError, TimeoutError:
await script_obj.async_stop()
raise
else:
@@ -1310,7 +1310,7 @@ async def test_wait_timeout(
assert script_obj.is_running
assert len(events) == 0
except (AssertionError, TimeoutError):
except AssertionError, TimeoutError:
await script_obj.async_stop()
raise
else:
@@ -1371,7 +1371,7 @@ async def test_wait_trigger_with_zero_timeout(
try:
await asyncio.wait_for(wait_started_flag.wait(), 1)
except (AssertionError, TimeoutError):
except AssertionError, TimeoutError:
await script_obj.async_stop()
raise
@@ -1419,7 +1419,7 @@ async def test_wait_trigger_matches_with_zero_timeout(
try:
await asyncio.wait_for(wait_started_flag.wait(), 1)
except (AssertionError, TimeoutError):
except AssertionError, TimeoutError:
await script_obj.async_stop()
raise
@@ -1461,7 +1461,7 @@ async def test_wait_template_with_zero_timeout(
try:
await asyncio.wait_for(wait_started_flag.wait(), 1)
except (AssertionError, TimeoutError):
except AssertionError, TimeoutError:
await script_obj.async_stop()
raise
@@ -1502,7 +1502,7 @@ async def test_wait_template_matches_with_zero_timeout(
try:
await asyncio.wait_for(wait_started_flag.wait(), 1)
except (AssertionError, TimeoutError):
except AssertionError, TimeoutError:
await script_obj.async_stop()
raise
@@ -1557,7 +1557,7 @@ async def test_wait_continue_on_timeout(
assert script_obj.is_running
assert len(events) == 0
except (AssertionError, TimeoutError):
except AssertionError, TimeoutError:
await script_obj.async_stop()
raise
else:
@@ -1599,7 +1599,7 @@ async def test_wait_template_variables_in(hass: HomeAssistant) -> None:
await asyncio.wait_for(wait_started_flag.wait(), 1)
assert script_obj.is_running
except (AssertionError, TimeoutError):
except AssertionError, TimeoutError:
await script_obj.async_stop()
raise
else:
@@ -1640,7 +1640,7 @@ async def test_wait_template_with_utcnow(hass: HomeAssistant) -> None:
match_time = start_time.replace(hour=12)
with freeze_time(match_time):
async_fire_time_changed(hass, match_time)
except (AssertionError, TimeoutError):
except AssertionError, TimeoutError:
await script_obj.async_stop()
raise
else:
@@ -1741,7 +1741,7 @@ async def test_wait_variables_out(hass: HomeAssistant, mode, action_type) -> Non
assert script_obj.is_running
assert len(events) == 0
except (AssertionError, TimeoutError):
except AssertionError, TimeoutError:
await script_obj.async_stop()
raise
else:
@@ -5015,7 +5015,7 @@ async def test_script_mode_single(
assert "Already running" in caplog.text
assert script_obj.is_running
except (AssertionError, TimeoutError):
except AssertionError, TimeoutError:
await script_obj.async_stop()
raise
else:
@@ -5152,7 +5152,7 @@ async def test_script_mode_2(
)
for message in messages
)
except (AssertionError, TimeoutError):
except AssertionError, TimeoutError:
await script_obj.async_stop()
raise
else:
@@ -5247,7 +5247,7 @@ async def test_script_mode_queued(hass: HomeAssistant) -> None:
assert script_obj.runs == 1
assert len(events) == 3
assert events[2].data["value"] == 1
except (AssertionError, TimeoutError):
except AssertionError, TimeoutError:
await script_obj.async_stop()
raise
else:
@@ -5299,7 +5299,7 @@ async def test_script_mode_queued_cancel(hass: HomeAssistant) -> None:
assert not script_obj.is_running
assert script_obj.runs == 0
except (AssertionError, TimeoutError):
except AssertionError, TimeoutError:
await script_obj.async_stop()
raise
@@ -5360,7 +5360,7 @@ async def test_shutdown_at(
assert script_obj.is_running
assert script_obj.last_action == delay_alias
except (AssertionError, TimeoutError):
except AssertionError, TimeoutError:
await script_obj.async_stop()
raise
else:
@@ -5396,7 +5396,7 @@ async def test_shutdown_after(
assert script_obj.is_running
assert script_obj.last_action == delay_alias
except (AssertionError, TimeoutError):
except AssertionError, TimeoutError:
await script_obj.async_stop()
raise
else: