diff --git a/homeassistant/components/acer_projector/switch.py b/homeassistant/components/acer_projector/switch.py index 747c7c98d73..f3e4b3b03e5 100644 --- a/homeassistant/components/acer_projector/switch.py +++ b/homeassistant/components/acer_projector/switch.py @@ -111,8 +111,7 @@ class AcerSwitch(SwitchEntity): """Write msg, obtain answer and format output.""" # answers are formatted as ***\answer\r*** awns = self._write_read(msg) - match = re.search(r"\r(.+)\r", awns) - if match: + if match := re.search(r"\r(.+)\r", awns): return match.group(1) return STATE_UNKNOWN diff --git a/homeassistant/components/blueprint/importer.py b/homeassistant/components/blueprint/importer.py index 99dffb114e1..de39741d8ed 100644 --- a/homeassistant/components/blueprint/importer.py +++ b/homeassistant/components/blueprint/importer.py @@ -59,9 +59,7 @@ def _get_github_import_url(url: str) -> str: if url.startswith("https://raw.githubusercontent.com/"): return url - match = GITHUB_FILE_PATTERN.match(url) - - if match is None: + if (match := GITHUB_FILE_PATTERN.match(url)) is None: raise UnsupportedUrl("Not a GitHub file url") repo, path = match.groups() @@ -74,8 +72,7 @@ def _get_community_post_import_url(url: str) -> str: Async friendly. """ - match = COMMUNITY_TOPIC_PATTERN.match(url) - if match is None: + if (match := COMMUNITY_TOPIC_PATTERN.match(url)) is None: raise UnsupportedUrl("Not a topic url") _topic, post = match.groups() diff --git a/homeassistant/components/conversation/default_agent.py b/homeassistant/components/conversation/default_agent.py index d957eb8e0b2..405a4f818f4 100644 --- a/homeassistant/components/conversation/default_agent.py +++ b/homeassistant/components/conversation/default_agent.py @@ -118,9 +118,7 @@ class DefaultAgent(AbstractConversationAgent): for intent_type, matchers in intents.items(): for matcher in matchers: - match = matcher.match(text) - - if not match: + if not (match := matcher.match(text)): continue return await intent.async_handle( diff --git a/homeassistant/components/history/__init__.py b/homeassistant/components/history/__init__.py index 2ac9a77c025..960b9749220 100644 --- a/homeassistant/components/history/__init__.py +++ b/homeassistant/components/history/__init__.py @@ -130,16 +130,14 @@ async def ws_get_statistics_during_period( start_time_str = msg["start_time"] end_time_str = msg.get("end_time") - start_time = dt_util.parse_datetime(start_time_str) - if start_time: + if start_time := dt_util.parse_datetime(start_time_str): start_time = dt_util.as_utc(start_time) else: connection.send_error(msg["id"], "invalid_start_time", "Invalid start_time") return if end_time_str: - end_time = dt_util.parse_datetime(end_time_str) - if end_time: + if end_time := dt_util.parse_datetime(end_time_str): end_time = dt_util.as_utc(end_time) else: connection.send_error(msg["id"], "invalid_end_time", "Invalid end_time") @@ -194,11 +192,8 @@ class HistoryPeriodView(HomeAssistantView): ) -> web.Response: """Return history over a period of time.""" datetime_ = None - if datetime: - datetime_ = dt_util.parse_datetime(datetime) - - if datetime_ is None: - return self.json_message("Invalid datetime", HTTPStatus.BAD_REQUEST) + if datetime and (datetime_ := dt_util.parse_datetime(datetime)) is None: + return self.json_message("Invalid datetime", HTTPStatus.BAD_REQUEST) now = dt_util.utcnow() @@ -212,8 +207,7 @@ class HistoryPeriodView(HomeAssistantView): return self.json([]) if end_time_str := request.query.get("end_time"): - end_time = dt_util.parse_datetime(end_time_str) - if end_time: + if end_time := dt_util.parse_datetime(end_time_str): end_time = dt_util.as_utc(end_time) else: return self.json_message("Invalid end_time", HTTPStatus.BAD_REQUEST) diff --git a/homeassistant/components/input_datetime/__init__.py b/homeassistant/components/input_datetime/__init__.py index d1a89fca67b..c25680b7180 100644 --- a/homeassistant/components/input_datetime/__init__.py +++ b/homeassistant/components/input_datetime/__init__.py @@ -87,19 +87,16 @@ def valid_initial(conf): return conf if conf[CONF_HAS_DATE] and conf[CONF_HAS_TIME]: - parsed_value = dt_util.parse_datetime(initial) - if parsed_value is not None: + if dt_util.parse_datetime(initial) is not None: return conf raise vol.Invalid(f"Initial value '{initial}' can't be parsed as a datetime") if conf[CONF_HAS_DATE]: - parsed_value = dt_util.parse_date(initial) - if parsed_value is not None: + if dt_util.parse_date(initial) is not None: return conf raise vol.Invalid(f"Initial value '{initial}' can't be parsed as a date") - parsed_value = dt_util.parse_time(initial) - if parsed_value is not None: + if dt_util.parse_time(initial) is not None: return conf raise vol.Invalid(f"Initial value '{initial}' can't be parsed as a time") @@ -282,15 +279,13 @@ class InputDatetime(RestoreEntity): current_datetime = date_time elif self.has_date: - date = dt_util.parse_date(old_state.state) - if date is None: + if (date := dt_util.parse_date(old_state.state)) is None: current_datetime = dt_util.parse_datetime(default_value) else: current_datetime = py_datetime.datetime.combine(date, DEFAULT_TIME) else: - time = dt_util.parse_time(old_state.state) - if time is None: + if (time := dt_util.parse_time(old_state.state)) is None: current_datetime = dt_util.parse_datetime(default_value) else: current_datetime = py_datetime.datetime.combine( diff --git a/homeassistant/components/lcn/helpers.py b/homeassistant/components/lcn/helpers.py index 657657ea1d0..feb27e337e8 100644 --- a/homeassistant/components/lcn/helpers.py +++ b/homeassistant/components/lcn/helpers.py @@ -385,8 +385,7 @@ def is_address(value: str) -> tuple[AddressType, str]: myhome.0.g11 myhome.s0.g11 """ - matcher = PATTERN_ADDRESS.match(value) - if matcher: + if matcher := PATTERN_ADDRESS.match(value): is_group = matcher.group("type") == "g" addr = (int(matcher.group("seg_id")), int(matcher.group("id")), is_group) conn_id = matcher.group("conn_id") diff --git a/homeassistant/components/litterrobot/entity.py b/homeassistant/components/litterrobot/entity.py index fbcd129411a..5a6590f9360 100644 --- a/homeassistant/components/litterrobot/entity.py +++ b/homeassistant/components/litterrobot/entity.py @@ -99,9 +99,7 @@ class LitterRobotControlEntity(LitterRobotEntity): @staticmethod def parse_time_at_default_timezone(time_str: str) -> time | None: """Parse a time string and add default timezone.""" - parsed_time = dt_util.parse_time(time_str) - - if parsed_time is None: + if (parsed_time := dt_util.parse_time(time_str)) is None: return None return ( diff --git a/homeassistant/components/minio/minio_helper.py b/homeassistant/components/minio/minio_helper.py index b7fb3157c71..4f10da10998 100644 --- a/homeassistant/components/minio/minio_helper.py +++ b/homeassistant/components/minio/minio_helper.py @@ -22,8 +22,7 @@ def normalize_metadata(metadata: dict) -> dict: """Normalize object metadata by stripping the prefix.""" new_metadata = {} for meta_key, meta_value in metadata.items(): - match = _METADATA_RE.match(meta_key) - if not match: + if not (match := _METADATA_RE.match(meta_key)): continue new_metadata[match.group(1).lower()] = meta_value diff --git a/homeassistant/components/mqtt/discovery.py b/homeassistant/components/mqtt/discovery.py index ffc0c1de435..d8ab9193cc4 100644 --- a/homeassistant/components/mqtt/discovery.py +++ b/homeassistant/components/mqtt/discovery.py @@ -97,9 +97,8 @@ async def async_start( # noqa: C901 payload = msg.payload topic = msg.topic topic_trimmed = topic.replace(f"{discovery_topic}/", "", 1) - match = TOPIC_MATCHER.match(topic_trimmed) - if not match: + if not (match := TOPIC_MATCHER.match(topic_trimmed)): if topic_trimmed.endswith("config"): _LOGGER.warning( "Received message on illegal discovery topic '%s'", topic diff --git a/homeassistant/components/openuv/sensor.py b/homeassistant/components/openuv/sensor.py index f1d0ba9e0b1..bcfac6e3684 100644 --- a/homeassistant/components/openuv/sensor.py +++ b/homeassistant/components/openuv/sensor.py @@ -157,8 +157,7 @@ class OpenUvSensor(OpenUvEntity, SensorEntity): self._attr_native_value = UV_LEVEL_LOW elif self.entity_description.key == TYPE_MAX_UV_INDEX: self._attr_native_value = data["uv_max"] - uv_max_time = parse_datetime(data["uv_max_time"]) - if uv_max_time: + if uv_max_time := parse_datetime(data["uv_max_time"]): self._attr_extra_state_attributes.update( {ATTR_MAX_UV_TIME: as_local(uv_max_time)} ) diff --git a/homeassistant/components/script/__init__.py b/homeassistant/components/script/__init__.py index b07cc2325b1..14160268073 100644 --- a/homeassistant/components/script/__init__.py +++ b/homeassistant/components/script/__init__.py @@ -96,9 +96,7 @@ def entities_in_script(hass: HomeAssistant, entity_id: str) -> list[str]: component = hass.data[DOMAIN] - script_entity = component.get_entity(entity_id) - - if script_entity is None: + if (script_entity := component.get_entity(entity_id)) is None: return [] return list(script_entity.script.referenced_entities) @@ -127,9 +125,7 @@ def devices_in_script(hass: HomeAssistant, entity_id: str) -> list[str]: component = hass.data[DOMAIN] - script_entity = component.get_entity(entity_id) - - if script_entity is None: + if (script_entity := component.get_entity(entity_id)) is None: return [] return list(script_entity.script.referenced_devices) @@ -158,9 +154,7 @@ def areas_in_script(hass: HomeAssistant, entity_id: str) -> list[str]: component = hass.data[DOMAIN] - script_entity = component.get_entity(entity_id) - - if script_entity is None: + if (script_entity := component.get_entity(entity_id)) is None: return [] return list(script_entity.script.referenced_areas) diff --git a/homeassistant/components/tts/__init__.py b/homeassistant/components/tts/__init__.py index 00e1dae6a8c..e2fddf3afe5 100644 --- a/homeassistant/components/tts/__init__.py +++ b/homeassistant/components/tts/__init__.py @@ -462,8 +462,7 @@ class SpeechManager: This method is a coroutine. """ - record = _RE_VOICE_FILE.match(filename.lower()) - if not record: + if not (record := _RE_VOICE_FILE.match(filename.lower())): raise HomeAssistantError("Wrong tts file format!") key = KEY_PATTERN.format( @@ -571,8 +570,7 @@ def _get_cache_files(cache_dir): folder_data = os.listdir(cache_dir) for file_data in folder_data: - record = _RE_VOICE_FILE.match(file_data) - if record: + if record := _RE_VOICE_FILE.match(file_data): key = KEY_PATTERN.format( record.group(1), record.group(2), record.group(3), record.group(4) ) diff --git a/homeassistant/components/xiaomi_miio/config_flow.py b/homeassistant/components/xiaomi_miio/config_flow.py index 96a06f6a33d..744d80494c8 100644 --- a/homeassistant/components/xiaomi_miio/config_flow.py +++ b/homeassistant/components/xiaomi_miio/config_flow.py @@ -161,8 +161,7 @@ class XiaomiMiioFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): self.mac = discovery_info.get("properties", {}).get("mac") if self.mac is None: poch = discovery_info.get("properties", {}).get("poch", "") - result = search(r"mac=\w+", poch) - if result is not None: + if (result := search(r"mac=\w+", poch)) is not None: self.mac = result.group(0).split("=")[1] if not name or not self.host or not self.mac: diff --git a/homeassistant/helpers/entity_component.py b/homeassistant/helpers/entity_component.py index d65f485166b..fb1abcbf7e9 100644 --- a/homeassistant/helpers/entity_component.py +++ b/homeassistant/helpers/entity_component.py @@ -49,9 +49,7 @@ async def async_update_entity(hass: HomeAssistant, entity_id: str) -> None: ) return - entity_obj = entity_comp.get_entity(entity_id) - - if entity_obj is None: + if (entity_obj := entity_comp.get_entity(entity_id)) is None: logging.getLogger(__name__).warning( "Forced update failed. Entity %s not found.", entity_id ) diff --git a/homeassistant/helpers/intent.py b/homeassistant/helpers/intent.py index a153d994471..d3494c3f41b 100644 --- a/homeassistant/helpers/intent.py +++ b/homeassistant/helpers/intent.py @@ -168,8 +168,7 @@ def _fuzzymatch(name: str, items: Iterable[T], key: Callable[[T], str]) -> T | N pattern = ".*?".join(name) regex = re.compile(pattern, re.IGNORECASE) for idx, item in enumerate(items): - match = regex.search(key(item)) - if match: + if match := regex.search(key(item)): # Add key length so we prefer shorter keys with the same group and start. # Add index so we pick first match in case same group, start, and key length. matches.append(