From 0496d5b149438fca18c4b96f5c10610718afc124 Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Wed, 19 Jul 2023 12:52:33 +0200 Subject: [PATCH] Fix --- homeassistant/block_async_io.py | 3 +-- homeassistant/components/airzone_cloud/climate.py | 9 +++------ .../components/amberelectric/coordinator.py | 3 +-- homeassistant/components/aosmith/water_heater.py | 3 +-- homeassistant/components/apple_tv/config_flow.py | 3 +-- .../components/assist_pipeline/pipeline.py | 6 ++---- .../components/assist_satellite/websocket_api.py | 12 ++++-------- .../components/bayesian/binary_sensor.py | 3 +-- homeassistant/components/blue_current/sensor.py | 4 +--- .../components/bluesound/media_player.py | 9 +++------ .../bluetooth/passive_update_processor.py | 2 +- .../components/cambridge_audio/media_player.py | 6 ++---- homeassistant/components/camera/helper.py | 3 +-- homeassistant/components/climate/__init__.py | 3 +-- homeassistant/components/command_line/utils.py | 3 +-- homeassistant/components/control4/media_player.py | 12 ++++-------- homeassistant/components/conversation/__init__.py | 12 +++--------- .../components/conversation/agent_manager.py | 4 +--- .../components/conversation/default_agent.py | 6 ++---- homeassistant/components/conversation/http.py | 4 +--- homeassistant/components/conversation/trace.py | 3 +-- homeassistant/components/devialet/media_player.py | 4 +--- .../components/dwd_weather_warnings/util.py | 12 ++++-------- homeassistant/components/ecobee/climate.py | 3 +-- homeassistant/components/ecovacs/vacuum.py | 3 +-- homeassistant/components/elmax/cover.py | 3 +-- homeassistant/components/emoncms/__init__.py | 3 +-- homeassistant/components/emoncms/sensor.py | 6 ++---- homeassistant/components/emulated_hue/hue_api.py | 3 +-- homeassistant/components/enphase_envoy/sensor.py | 3 +-- .../components/esphome/assist_satellite.py | 3 +-- homeassistant/components/esphome/manager.py | 3 +-- homeassistant/components/fitbit/sensor.py | 3 +-- homeassistant/components/flux_led/util.py | 3 +-- homeassistant/components/fritzbox/climate.py | 6 ++---- .../components/fujitsu_fglair/__init__.py | 3 +-- .../components/generic_hygrostat/humidifier.py | 3 +-- homeassistant/components/google/calendar.py | 3 +-- homeassistant/components/google_cloud/tts.py | 3 +-- homeassistant/components/hassio/coordinator.py | 3 +-- homeassistant/components/hive/climate.py | 3 +-- homeassistant/components/hive/light.py | 3 +-- homeassistant/components/hive/sensor.py | 3 +-- homeassistant/components/hive/switch.py | 3 +-- homeassistant/components/hive/water_heater.py | 3 +-- homeassistant/components/home_connect/time.py | 6 ++---- homeassistant/components/homeassistant/scene.py | 3 +-- .../homeassistant/triggers/numeric_state.py | 3 +-- homeassistant/components/homekit/type_covers.py | 3 +-- homeassistant/components/huum/climate.py | 3 +-- homeassistant/components/image/media_source.py | 4 +--- homeassistant/components/insteon/config_flow.py | 3 +-- homeassistant/components/integration/sensor.py | 3 +-- homeassistant/components/intent/timers.py | 15 +++++---------- homeassistant/components/ipma/weather.py | 4 +--- homeassistant/components/iskra/entity.py | 3 +-- homeassistant/components/knx/__init__.py | 6 ++---- homeassistant/components/lg_thinq/mqtt.py | 3 +-- homeassistant/components/lifx/manager.py | 3 +-- homeassistant/components/linkplay/media_player.py | 12 ++++-------- homeassistant/components/lutron_caseta/util.py | 3 +-- homeassistant/components/madvr/config_flow.py | 3 +-- homeassistant/components/mastodon/notify.py | 3 +-- homeassistant/components/matter/__init__.py | 4 +--- homeassistant/components/matter/helpers.py | 3 +-- homeassistant/components/mealie/calendar.py | 3 +-- homeassistant/components/modbus/validators.py | 2 +- homeassistant/components/mqtt/diagnostics.py | 3 +-- .../components/mqtt_statestream/__init__.py | 3 +-- homeassistant/components/nasweb/__init__.py | 6 ++---- homeassistant/components/nasweb/config_flow.py | 3 +-- homeassistant/components/nextbus/sensor.py | 5 +---- .../components/ondilo_ico/coordinator.py | 3 +-- homeassistant/components/onkyo/config_flow.py | 3 +-- homeassistant/components/onkyo/media_player.py | 3 +-- .../components/openweathermap/__init__.py | 3 +-- homeassistant/components/osoenergy/__init__.py | 10 +++++----- .../components/osoenergy/water_heater.py | 3 +-- .../atlantic_pass_apc_zone_control_zone.py | 3 +-- homeassistant/components/prometheus/__init__.py | 4 +--- .../components/python_script/__init__.py | 3 +-- homeassistant/components/rainbird/calendar.py | 6 ++---- .../components/rainforest_raven/config_flow.py | 3 +-- homeassistant/components/recorder/db_schema.py | 3 +-- homeassistant/components/reolink/entity.py | 6 ++---- homeassistant/components/ring/camera.py | 3 +-- homeassistant/components/roborock/__init__.py | 3 +-- homeassistant/components/sabnzbd/__init__.py | 3 +-- homeassistant/components/sabnzbd/config_flow.py | 3 +-- homeassistant/components/shelly/utils.py | 4 +--- homeassistant/components/smlight/config_flow.py | 3 +-- homeassistant/components/snapcast/media_player.py | 3 +-- homeassistant/components/solarlog/sensor.py | 4 +--- homeassistant/components/soma/sensor.py | 3 +-- homeassistant/components/sonos/speaker.py | 3 +-- .../components/streamlabswater/config_flow.py | 3 +-- .../swiss_public_transport/coordinator.py | 4 +--- homeassistant/components/tami4/config_flow.py | 3 +-- homeassistant/components/template/__init__.py | 4 +--- homeassistant/components/tesla_fleet/select.py | 6 ++---- homeassistant/components/teslemetry/climate.py | 3 +-- homeassistant/components/todo/__init__.py | 3 +-- homeassistant/components/tplink/entity.py | 3 +-- homeassistant/components/tplink_lte/notify.py | 2 +- .../components/tplink_omada/binary_sensor.py | 3 +-- homeassistant/components/tplink_omada/switch.py | 3 +-- homeassistant/components/trace/util.py | 3 +-- homeassistant/components/tts/__init__.py | 6 ++---- .../components/unifi_direct/device_tracker.py | 3 +-- homeassistant/components/unifiprotect/data.py | 3 +-- homeassistant/components/utility_meter/sensor.py | 2 +- homeassistant/components/verisure/lock.py | 6 ++---- homeassistant/components/voip/assist_satellite.py | 3 +-- homeassistant/components/wake_word/__init__.py | 4 +--- homeassistant/components/weatherkit/weather.py | 6 ++---- homeassistant/components/wyoming/number.py | 3 +-- homeassistant/components/zha/helpers.py | 3 +-- homeassistant/components/zwave_js/event.py | 3 +-- homeassistant/helpers/check_config.py | 3 +-- homeassistant/helpers/intent.py | 3 +-- homeassistant/helpers/llm.py | 7 ++----- homeassistant/helpers/network.py | 3 +-- homeassistant/helpers/significant_change.py | 4 +--- homeassistant/helpers/trace.py | 3 +-- tests/components/api/test_init.py | 4 +--- .../components/assist_pipeline/test_websocket.py | 6 ++---- tests/components/august/mocks.py | 12 +++++------- tests/components/homekit_controller/common.py | 3 +-- tests/components/lutron_caseta/__init__.py | 4 +--- tests/components/madvr/conftest.py | 4 +--- tests/components/recorder/db_schema_25.py | 15 +++++++++++---- tests/components/recorder/db_schema_28.py | 15 +++++++++++---- tests/components/recorder/db_schema_30.py | 14 ++++++++++---- tests/components/recorder/db_schema_32.py | 14 ++++++++++---- tests/components/recorder/db_schema_42.py | 13 +++++-------- tests/components/recorder/db_schema_43.py | 9 +++------ tests/components/refoss/__init__.py | 3 +-- tests/components/stream/test_ll_hls.py | 12 ++++-------- tests/components/zha/common.py | 3 +-- tests/conftest.py | 4 +--- tests/helpers/test_schema_config_entry_flow.py | 4 +--- tests/helpers/test_template.py | 3 +-- tests/test_config_entries.py | 3 +-- tests/test_data_entry_flow.py | 4 +--- 144 files changed, 237 insertions(+), 418 deletions(-) diff --git a/homeassistant/block_async_io.py b/homeassistant/block_async_io.py index 7a68b2515e995b..431d75fd2ee256 100644 --- a/homeassistant/block_async_io.py +++ b/homeassistant/block_async_io.py @@ -232,8 +232,7 @@ class BlockedCalls: def enable() -> None: """Enable the detection of blocking calls in the event loop.""" - calls = _BLOCKED_CALLS.calls - if calls: + if calls := _BLOCKED_CALLS.calls: raise RuntimeError("Blocking call detection is already enabled") loop_thread_id = threading.get_ident() diff --git a/homeassistant/components/airzone_cloud/climate.py b/homeassistant/components/airzone_cloud/climate.py index b98473072e467c..4dec619afc8a1c 100644 --- a/homeassistant/components/airzone_cloud/climate.py +++ b/homeassistant/components/airzone_cloud/climate.py @@ -279,8 +279,7 @@ def _initialize_fan_speeds(self) -> None: self._speeds = {} for key, value in fan_speeds.items(): - _key = azd_speeds.get(key) - if _key is not None: + if (_key := azd_speeds.get(key)) is not None: self._speeds[_key] = value self._speeds_reverse = {v: k for k, v in self._speeds.items()} @@ -317,8 +316,7 @@ async def async_set_fan_mode(self, fan_mode: str) -> None: async def async_set_temperature(self, **kwargs: Any) -> None: """Set new target temperature.""" - hvac_mode = kwargs.get(ATTR_HVAC_MODE) - if hvac_mode is not None: + if (hvac_mode := kwargs.get(ATTR_HVAC_MODE)) is not None: await self.async_set_hvac_mode(hvac_mode) params: dict[str, Any] = {} @@ -374,8 +372,7 @@ async def async_turn_off(self) -> None: async def async_set_temperature(self, **kwargs: Any) -> None: """Set new target temperature.""" - hvac_mode = kwargs.get(ATTR_HVAC_MODE) - if hvac_mode is not None: + if (hvac_mode := kwargs.get(ATTR_HVAC_MODE)) is not None: await self.async_set_hvac_mode(hvac_mode) params: dict[str, Any] = {} diff --git a/homeassistant/components/amberelectric/coordinator.py b/homeassistant/components/amberelectric/coordinator.py index 57028e07d21d45..15e209188c4316 100644 --- a/homeassistant/components/amberelectric/coordinator.py +++ b/homeassistant/components/amberelectric/coordinator.py @@ -112,8 +112,7 @@ def update_price_data(self) -> dict[str, dict[str, Any]]: ] result["grid"]["renewables"] = round(general[0].renewables) result["grid"]["price_spike"] = general[0].spike_status.value - tariff_information = general[0].tariff_information - if tariff_information: + if tariff_information := general[0].tariff_information: result["grid"]["demand_window"] = tariff_information.demand_window controlled_load = [ diff --git a/homeassistant/components/aosmith/water_heater.py b/homeassistant/components/aosmith/water_heater.py index f3dc8b3413f52d..54bacedbba20ad 100644 --- a/homeassistant/components/aosmith/water_heater.py +++ b/homeassistant/components/aosmith/water_heater.py @@ -138,8 +138,7 @@ async def async_set_operation_mode(self, operation_mode: str) -> None: async def async_set_temperature(self, **kwargs: Any) -> None: """Set new target temperature.""" - temperature = kwargs.get("temperature") - if temperature is not None: + if (temperature := kwargs.get("temperature")) is not None: await self.client.update_setpoint(self.junction_id, temperature) await self.coordinator.async_request_refresh() diff --git a/homeassistant/components/apple_tv/config_flow.py b/homeassistant/components/apple_tv/config_flow.py index b0741cc9c61589..f5752b3603c9cb 100644 --- a/homeassistant/components/apple_tv/config_flow.py +++ b/homeassistant/components/apple_tv/config_flow.py @@ -425,9 +425,8 @@ async def async_pair_next_protocol(self) -> ConfigFlowResult: self.protocol = self.protocols_to_pair.popleft() assert self.atv - service = self.atv.get_service(self.protocol) - if service is None: + if (service := self.atv.get_service(self.protocol)) is None: _LOGGER.debug( "%s does not support pairing (cannot find a corresponding service)", self.protocol, diff --git a/homeassistant/components/assist_pipeline/pipeline.py b/homeassistant/components/assist_pipeline/pipeline.py index 9e9e84fb5d6ea1..f1e8856b78ed75 100644 --- a/homeassistant/components/assist_pipeline/pipeline.py +++ b/homeassistant/components/assist_pipeline/pipeline.py @@ -1328,8 +1328,7 @@ def _pipeline_debug_recording_thread_proc( run_recording_dir.mkdir(parents=True, exist_ok=True) while True: - message = queue.get(timeout=message_timeout) - if message is None: + if (message := queue.get(timeout=message_timeout)) is None: # Stop signal break @@ -1702,8 +1701,7 @@ def ws_get_item( self, hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict ) -> None: """Get an item.""" - item_id = msg.get(self.item_id_key) - if item_id is None: + if (item_id := msg.get(self.item_id_key)) is None: item_id = self.storage_collection.async_get_preferred_item() if item_id.startswith("conversation.") and hass.states.get(item_id): diff --git a/homeassistant/components/assist_satellite/websocket_api.py b/homeassistant/components/assist_satellite/websocket_api.py index c81648c6ee360e..f9e2d6991d2bec 100644 --- a/homeassistant/components/assist_satellite/websocket_api.py +++ b/homeassistant/components/assist_satellite/websocket_api.py @@ -48,8 +48,7 @@ async def websocket_intercept_wake_word( msg: dict[str, Any], ) -> None: """Intercept the next wake word from a satellite.""" - satellite = hass.data[DATA_COMPONENT].get_entity(msg["entity_id"]) - if satellite is None: + if (satellite := hass.data[DATA_COMPONENT].get_entity(msg["entity_id"])) is None: connection.send_error( msg["id"], websocket_api.ERR_NOT_FOUND, "Entity not found" ) @@ -86,8 +85,7 @@ def websocket_get_configuration( msg: dict[str, Any], ) -> None: """Get the current satellite configuration.""" - satellite = hass.data[DATA_COMPONENT].get_entity(msg["entity_id"]) - if satellite is None: + if (satellite := hass.data[DATA_COMPONENT].get_entity(msg["entity_id"])) is None: connection.send_error( msg["id"], websocket_api.ERR_NOT_FOUND, "Entity not found" ) @@ -115,8 +113,7 @@ async def websocket_set_wake_words( msg: dict[str, Any], ) -> None: """Set the active wake words for the satellite.""" - satellite = hass.data[DATA_COMPONENT].get_entity(msg["entity_id"]) - if satellite is None: + if (satellite := hass.data[DATA_COMPONENT].get_entity(msg["entity_id"])) is None: connection.send_error( msg["id"], websocket_api.ERR_NOT_FOUND, "Entity not found" ) @@ -168,8 +165,7 @@ async def websocket_test_connection( Send an announcement to the device with a special media id. """ component: EntityComponent[AssistSatelliteEntity] = hass.data[DOMAIN] - satellite = component.get_entity(msg["entity_id"]) - if satellite is None: + if (satellite := component.get_entity(msg["entity_id"])) is None: connection.send_error( msg["id"], websocket_api.ERR_NOT_FOUND, "Entity not found" ) diff --git a/homeassistant/components/bayesian/binary_sensor.py b/homeassistant/components/bayesian/binary_sensor.py index 6d203c344f222d..b3558ebeeb3fc0 100644 --- a/homeassistant/components/bayesian/binary_sensor.py +++ b/homeassistant/components/bayesian/binary_sensor.py @@ -505,8 +505,7 @@ def _process_numeric_state( if TYPE_CHECKING: assert entity_id is not None - entity = self.hass.states.get(entity_id) - if entity is None: + if (entity := self.hass.states.get(entity_id)) is None: return None try: diff --git a/homeassistant/components/blue_current/sensor.py b/homeassistant/components/blue_current/sensor.py index be39e9571ec44a..236aee4acc453a 100644 --- a/homeassistant/components/blue_current/sensor.py +++ b/homeassistant/components/blue_current/sensor.py @@ -302,9 +302,7 @@ def __init__( def update_from_latest_data(self) -> None: """Update the grid sensor from the latest data.""" - new_value = self.connector.grid.get(self.key) - - if new_value is not None: + if (new_value := self.connector.grid.get(self.key)) is not None: self.has_value = True self._attr_native_value = new_value diff --git a/homeassistant/components/bluesound/media_player.py b/homeassistant/components/bluesound/media_player.py index 38ef78fad3a7da..95785958e722d3 100644 --- a/homeassistant/components/bluesound/media_player.py +++ b/homeassistant/components/bluesound/media_player.py @@ -399,8 +399,7 @@ def media_image_url(self) -> str | None: if self._status is None or (self.is_grouped and not self.is_master): return None - url = self._status.image - if url is None: + if (url := self._status.image) is None: return None if url[0] == "/": @@ -418,8 +417,7 @@ def media_position(self) -> int | None: if self._last_status_update is None or mediastate == MediaPlayerState.IDLE: return None - position = self._status.seconds - if position is None: + if (position := self._status.seconds) is None: return None if mediastate == MediaPlayerState.PLAYING: @@ -433,8 +431,7 @@ def media_duration(self) -> int | None: if self._status is None or (self.is_grouped and not self.is_master): return None - duration = self._status.total_seconds - if duration is None: + if (duration := self._status.total_seconds) is None: return None return int(duration) diff --git a/homeassistant/components/bluetooth/passive_update_processor.py b/homeassistant/components/bluetooth/passive_update_processor.py index 8f66a3582eabea..400a5448ead5ec 100644 --- a/homeassistant/components/bluetooth/passive_update_processor.py +++ b/homeassistant/components/bluetooth/passive_update_processor.py @@ -104,7 +104,7 @@ def deserialize_entity_description( # out, but it doesn't. If we end up using this in more # places we can add a `as_dict` and a `from_dict` # method to these classes - if field_name == CONF_ENTITY_CATEGORY: + if (field_name := field.name) == CONF_ENTITY_CATEGORY: value = try_parse_enum(EntityCategory, data.get(field_name)) else: value = data.get(field_name) diff --git a/homeassistant/components/cambridge_audio/media_player.py b/homeassistant/components/cambridge_audio/media_player.py index 9896effb07d810..2bb0b594896383 100644 --- a/homeassistant/components/cambridge_audio/media_player.py +++ b/homeassistant/components/cambridge_audio/media_player.py @@ -92,16 +92,14 @@ def supported_features(self) -> MediaPlayerEntityFeature: if TransportControl.PLAY_PAUSE in controls: features |= MediaPlayerEntityFeature.PLAY | MediaPlayerEntityFeature.PAUSE for control in controls: - feature = TRANSPORT_FEATURES.get(control) - if feature: + if feature := TRANSPORT_FEATURES.get(control): features |= feature return features @property def state(self) -> MediaPlayerState: """Return the state of the device.""" - media_state = self.client.play_state.state - if media_state == "NETWORK": + if (media_state := self.client.play_state.state) == "NETWORK": return MediaPlayerState.STANDBY if self.client.state.power: if media_state == "play": diff --git a/homeassistant/components/camera/helper.py b/homeassistant/components/camera/helper.py index 5e84b18dda8a03..dff53608785859 100644 --- a/homeassistant/components/camera/helper.py +++ b/homeassistant/components/camera/helper.py @@ -15,8 +15,7 @@ def get_camera_from_entity_id(hass: HomeAssistant, entity_id: str) -> Camera: """Get camera component from entity_id.""" - component = hass.data.get(DATA_COMPONENT) - if component is None: + if (component := hass.data.get(DATA_COMPONENT)) is None: raise HomeAssistantError("Camera integration not set up") if (camera := component.get_entity(entity_id)) is None: diff --git a/homeassistant/components/climate/__init__.py b/homeassistant/components/climate/__init__.py index ca85979f19a99e..30625ca49d4eb3 100644 --- a/homeassistant/components/climate/__init__.py +++ b/homeassistant/components/climate/__init__.py @@ -349,8 +349,7 @@ def _report_legacy_aux(self) -> None: @property def state(self) -> str | None: """Return the current state.""" - hvac_mode = self.hvac_mode - if hvac_mode is None: + if (hvac_mode := self.hvac_mode) is None: return None # Support hvac_mode as string for custom integration backwards compatibility if not isinstance(hvac_mode, HVACMode): diff --git a/homeassistant/components/command_line/utils.py b/homeassistant/components/command_line/utils.py index c1926546950378..eea53a05ed26ac 100644 --- a/homeassistant/components/command_line/utils.py +++ b/homeassistant/components/command_line/utils.py @@ -29,8 +29,7 @@ async def async_call_shell_with_timeout( _LOGGER.error("Timeout for command: %s", command) return -1 - return_code = proc.returncode - if return_code == _EXEC_FAILED_CODE: + if (return_code := proc.returncode) == _EXEC_FAILED_CODE: _LOGGER.error("Error trying to exec command: %s", command) elif log_return_code and return_code != 0: _LOGGER.error( diff --git a/homeassistant/components/control4/media_player.py b/homeassistant/components/control4/media_player.py index 9e3421817a341e..707450384ed97e 100644 --- a/homeassistant/components/control4/media_player.py +++ b/homeassistant/components/control4/media_player.py @@ -82,15 +82,13 @@ async def async_setup_entry( ) -> None: """Set up Control4 rooms from a config entry.""" entry_data = hass.data[DOMAIN][entry.entry_id] - ui_config = entry_data[CONF_UI_CONFIGURATION] # OS 2 will not have a ui_configuration - if not ui_config: + if not (ui_config := entry_data[CONF_UI_CONFIGURATION]): _LOGGER.debug("No UI Configuration found for Control4") return - all_rooms = await get_rooms(hass, entry) - if not all_rooms: + if not (all_rooms := await get_rooms(hass, entry)): return scan_interval = entry_data[CONF_SCAN_INTERVAL] @@ -233,8 +231,7 @@ def _get_current_video_device_id(self) -> int | None: return self._get_device_from_variable(CONTROL4_CURRENT_VIDEO_DEVICE) def _get_current_playing_device_id(self) -> int | None: - media_info = self._get_media_info() - if media_info: + if media_info := self._get_media_info(): if "medSrcDev" in media_info: return media_info["medSrcDev"] if "deviceid" in media_info: @@ -293,8 +290,7 @@ def source(self): @property def media_title(self) -> str | None: """Get the Media Title.""" - media_info = self._get_media_info() - if not media_info: + if not (media_info := self._get_media_info()): return None if "title" in media_info: return media_info["title"] diff --git a/homeassistant/components/conversation/__init__.py b/homeassistant/components/conversation/__init__.py index 898b7b2cf4fabd..f6404035bbf4d5 100644 --- a/homeassistant/components/conversation/__init__.py +++ b/homeassistant/components/conversation/__init__.py @@ -137,9 +137,7 @@ def async_get_conversation_languages( agents: list[ConversationEntity | AbstractConversationAgent] if agent_id: - agent = async_get_agent(hass, agent_id) - - if agent is None: + if (agent := async_get_agent(hass, agent_id)) is None: raise ValueError(f"Agent {agent_id} not found") # Shortcut @@ -175,9 +173,7 @@ def async_get_agent_info( agent_id: str | None = None, ) -> AgentInfo | None: """Get information on the agent or None if not found.""" - agent = async_get_agent(hass, agent_id) - - if agent is None: + if (agent := async_get_agent(hass, agent_id)) is None: return None if isinstance(agent, ConversationEntity): @@ -199,9 +195,7 @@ async def async_prepare_agent( hass: HomeAssistant, agent_id: str | None, language: str ) -> None: """Prepare given agent.""" - agent = async_get_agent(hass, agent_id) - - if agent is None: + if (agent := async_get_agent(hass, agent_id)) is None: raise ValueError("Invalid agent specified") await agent.async_prepare(language) diff --git a/homeassistant/components/conversation/agent_manager.py b/homeassistant/components/conversation/agent_manager.py index 7516d9d22efd21..11d55873ef6205 100644 --- a/homeassistant/components/conversation/agent_manager.py +++ b/homeassistant/components/conversation/agent_manager.py @@ -77,9 +77,7 @@ async def async_converse( device_id: str | None = None, ) -> ConversationResult: """Process text and get intent.""" - agent = async_get_agent(hass, agent_id) - - if agent is None: + if (agent := async_get_agent(hass, agent_id)) is None: raise ValueError(f"Agent {agent_id} not found") if isinstance(agent, ConversationEntity): diff --git a/homeassistant/components/conversation/default_agent.py b/homeassistant/components/conversation/default_agent.py index 66ffb25fa1a894..6cb848f301e0da 100644 --- a/homeassistant/components/conversation/default_agent.py +++ b/homeassistant/components/conversation/default_agent.py @@ -423,8 +423,7 @@ async def _async_process_intent_result( } for entity in result.entities_list } - device_area = self._get_device_area(user_input.device_id) - if device_area: + if device_area := self._get_device_area(user_input.device_id): slots["preferred_area_id"] = {"value": device_area.id} async_conversation_trace_append( ConversationTraceEventType.TOOL_CALL, @@ -1297,8 +1296,7 @@ async def _handle_trigger_result( response_text = "" response_set_by_trigger = False for trigger_future in asyncio.as_completed(trigger_callbacks): - trigger_response = await trigger_future - if trigger_response is None: + if (trigger_response := await trigger_future) is None: continue response_text = trigger_response diff --git a/homeassistant/components/conversation/http.py b/homeassistant/components/conversation/http.py index d9873c5cbce52e..7410049f733b29 100644 --- a/homeassistant/components/conversation/http.py +++ b/homeassistant/components/conversation/http.py @@ -81,9 +81,7 @@ async def websocket_prepare( msg: dict[str, Any], ) -> None: """Reload intents.""" - agent = async_get_agent(hass, msg.get("agent_id")) - - if agent is None: + if (agent := async_get_agent(hass, msg.get("agent_id"))) is None: connection.send_error(msg["id"], websocket_api.ERR_NOT_FOUND, "Agent not found") return diff --git a/homeassistant/components/conversation/trace.py b/homeassistant/components/conversation/trace.py index 6f993aa326a92c..00683b85365513 100644 --- a/homeassistant/components/conversation/trace.py +++ b/homeassistant/components/conversation/trace.py @@ -87,8 +87,7 @@ def async_conversation_trace_append( event_type: ConversationTraceEventType, event_data: dict[str, Any] ) -> None: """Append a ConversationTraceEvent to the current active trace.""" - trace = _current_trace.get() - if not trace: + if not (trace := _current_trace.get()): return trace.add_event(ConversationTraceEvent(event_type, event_data)) diff --git a/homeassistant/components/devialet/media_player.py b/homeassistant/components/devialet/media_player.py index d490e348b9c0bc..f7f5c47944bb72 100644 --- a/homeassistant/components/devialet/media_player.py +++ b/homeassistant/components/devialet/media_player.py @@ -99,9 +99,7 @@ def _handle_coordinator_update(self) -> None: @property def state(self) -> MediaPlayerState | None: """Return the state of the device.""" - playing_state = self.coordinator.client.playing_state - - if not playing_state: + if not (playing_state := self.coordinator.client.playing_state): return MediaPlayerState.IDLE if playing_state == "playing": return MediaPlayerState.PLAYING diff --git a/homeassistant/components/dwd_weather_warnings/util.py b/homeassistant/components/dwd_weather_warnings/util.py index 730ebf4b71e23d..1e4c96639bba97 100644 --- a/homeassistant/components/dwd_weather_warnings/util.py +++ b/homeassistant/components/dwd_weather_warnings/util.py @@ -14,23 +14,19 @@ def get_position_data( ) -> tuple[float, float] | None: """Extract longitude and latitude from a device tracker.""" registry = er.async_get(hass) - registry_entry = registry.async_get(registry_id) - if registry_entry is None: + if (registry_entry := registry.async_get(registry_id)) is None: raise EntityNotFoundError(f"Failed to find registry entry {registry_id}") - entity = hass.states.get(registry_entry.entity_id) - if entity is None: + if (entity := hass.states.get(registry_entry.entity_id)) is None: raise EntityNotFoundError(f"Failed to find entity {registry_entry.entity_id}") - latitude = entity.attributes.get(ATTR_LATITUDE) - if not latitude: + if not (latitude := entity.attributes.get(ATTR_LATITUDE)): raise AttributeError( f"Failed to find attribute '{ATTR_LATITUDE}' in {registry_entry.entity_id}", ATTR_LATITUDE, ) - longitude = entity.attributes.get(ATTR_LONGITUDE) - if not longitude: + if not (longitude := entity.attributes.get(ATTR_LONGITUDE)): raise AttributeError( f"Failed to find attribute '{ATTR_LONGITUDE}' in {registry_entry.entity_id}", ATTR_LONGITUDE, diff --git a/homeassistant/components/ecobee/climate.py b/homeassistant/components/ecobee/climate.py index 709926d8496029..90f594e72ad242 100644 --- a/homeassistant/components/ecobee/climate.py +++ b/homeassistant/components/ecobee/climate.py @@ -801,8 +801,7 @@ def set_humidity(self, humidity: int) -> None: def set_hvac_mode(self, hvac_mode: HVACMode) -> None: """Set HVAC mode (auto, auxHeatOnly, cool, heat, off).""" - ecobee_value = HASS_TO_ECOBEE_HVAC.get(hvac_mode) - if ecobee_value is None: + if (ecobee_value := HASS_TO_ECOBEE_HVAC.get(hvac_mode)) is None: _LOGGER.error("Invalid mode for set_hvac_mode: %s", hvac_mode) return self.data.ecobee.set_hvac_mode(self.thermostat_index, ecobee_value) diff --git a/homeassistant/components/ecovacs/vacuum.py b/homeassistant/components/ecovacs/vacuum.py index dde4fd64b5634b..04dd7cb3105c3d 100644 --- a/homeassistant/components/ecovacs/vacuum.py +++ b/homeassistant/components/ecovacs/vacuum.py @@ -307,8 +307,7 @@ def extra_state_attributes(self) -> Mapping[str, Any] | None: for room in self._rooms: # convert room name to snake_case to meet the convention room_name = slugify(room.name) - room_values = rooms.get(room_name) - if room_values is None: + if (room_values := rooms.get(room_name)) is None: rooms[room_name] = room.id elif isinstance(room_values, list): room_values.append(room.id) diff --git a/homeassistant/components/elmax/cover.py b/homeassistant/components/elmax/cover.py index 403bc51dbffab0..62ae7a3b74dcd4 100644 --- a/homeassistant/components/elmax/cover.py +++ b/homeassistant/components/elmax/cover.py @@ -113,8 +113,7 @@ async def async_stop_cover(self, **kwargs: Any) -> None: motion_status = self.coordinator.get_cover_state( self._device.endpoint_id ).status - command = _COMMAND_BY_MOTION_STATUS[motion_status] - if command: + if command := _COMMAND_BY_MOTION_STATUS[motion_status]: await self.coordinator.http_client.execute_command( endpoint_id=self._device.endpoint_id, command=command ) diff --git a/homeassistant/components/emoncms/__init__.py b/homeassistant/components/emoncms/__init__.py index 0cd686b5b56710..2326e00e1d3276 100644 --- a/homeassistant/components/emoncms/__init__.py +++ b/homeassistant/components/emoncms/__init__.py @@ -40,8 +40,7 @@ async def _check_unique_id_migration( hass: HomeAssistant, entry: EmonCMSConfigEntry, emoncms_client: EmoncmsClient ) -> None: """Check if we can migrate to the emoncms uuid.""" - emoncms_unique_id = await emoncms_client.async_get_uuid() - if emoncms_unique_id: + if emoncms_unique_id := await emoncms_client.async_get_uuid(): if entry.unique_id != emoncms_unique_id: _migrate_unique_id(hass, entry, emoncms_unique_id) else: diff --git a/homeassistant/components/emoncms/sensor.py b/homeassistant/components/emoncms/sensor.py index 9273c24c7dc629..38f7897219b17a 100644 --- a/homeassistant/components/emoncms/sensor.py +++ b/homeassistant/components/emoncms/sensor.py @@ -305,8 +305,7 @@ async def async_setup_entry( coordinator = entry.runtime_data # uuid was added in emoncms database 11.5.7 unique_id = entry.unique_id if entry.unique_id else entry.entry_id - elems = coordinator.data - if not elems: + if not (elems := coordinator.data): return sensors: list[EmonCmsSensor] = [] @@ -377,7 +376,6 @@ def _update_attributes(self, elem: dict[str, Any]) -> None: @callback def _handle_coordinator_update(self) -> None: """Handle updated data from the coordinator.""" - data = self.coordinator.data - if data: + if data := self.coordinator.data: self._update_attributes(data[self.idx]) super()._handle_coordinator_update() diff --git a/homeassistant/components/emulated_hue/hue_api.py b/homeassistant/components/emulated_hue/hue_api.py index e13112f20bb002..fd7409a30205ce 100644 --- a/homeassistant/components/emulated_hue/hue_api.py +++ b/homeassistant/components/emulated_hue/hue_api.py @@ -858,8 +858,7 @@ def state_supports_hue_brightness( state: State, color_modes: Iterable[ColorMode] ) -> bool: """Return True if the state supports brightness.""" - domain = state.domain - if domain == light.DOMAIN: + if (domain := state.domain) == light.DOMAIN: return light.brightness_supported(color_modes) if not (required_feature := DIMMABLE_SUPPORTED_FEATURES_BY_DOMAIN.get(domain)): return False diff --git a/homeassistant/components/enphase_envoy/sensor.py b/homeassistant/components/enphase_envoy/sensor.py index 20d610e4b71fcd..91a0c04b2ae797 100644 --- a/homeassistant/components/enphase_envoy/sensor.py +++ b/homeassistant/components/enphase_envoy/sensor.py @@ -1096,8 +1096,7 @@ def __init__( """Initialize Envoy inverter entity.""" super().__init__(coordinator, description) self._serial_number = serial_number - key = description.key - if key == INVERTERS_KEY: + if (key := description.key) == INVERTERS_KEY: # Originally there was only one inverter sensor, so we don't want to # break existing installations by changing the unique_id. self._attr_unique_id = serial_number diff --git a/homeassistant/components/esphome/assist_satellite.py b/homeassistant/components/esphome/assist_satellite.py index f60668b0a06c14..b952d6ea5638af 100644 --- a/homeassistant/components/esphome/assist_satellite.py +++ b/homeassistant/components/esphome/assist_satellite.py @@ -589,8 +589,7 @@ async def _stream_tts_audio( async def _wrap_audio_stream(self) -> AsyncIterable[bytes]: """Yield audio chunks from the queue until None.""" while True: - chunk = await self._audio_queue.get() - if not chunk: + if not (chunk := await self._audio_queue.get()): break yield chunk diff --git a/homeassistant/components/esphome/manager.py b/homeassistant/components/esphome/manager.py index 007b4e791e17ec..ac2ae459eed0e2 100644 --- a/homeassistant/components/esphome/manager.py +++ b/homeassistant/components/esphome/manager.py @@ -731,8 +731,7 @@ def _async_register_service( def _setup_services( hass: HomeAssistant, entry_data: RuntimeEntryData, services: list[UserService] ) -> None: - device_info = entry_data.device_info - if device_info is None: + if (device_info := entry_data.device_info) is None: # Can happen if device has never connected or .storage cleared return old_services = entry_data.services.copy() diff --git a/homeassistant/components/fitbit/sensor.py b/homeassistant/components/fitbit/sensor.py index d58dad4ca6720a..6ee18df95e0440 100644 --- a/homeassistant/components/fitbit/sensor.py +++ b/homeassistant/components/fitbit/sensor.py @@ -60,8 +60,7 @@ def _body_value_fn(result: dict[str, Any]) -> int | str: def _clock_format_12h(result: dict[str, Any]) -> str: - raw_state = result["value"] - if raw_state == "": + if (raw_state := result["value"]) == "": return "-" hours_str, minutes_str = raw_state.split(":") hours, minutes = int(hours_str), int(minutes_str) diff --git a/homeassistant/components/flux_led/util.py b/homeassistant/components/flux_led/util.py index 2691b841952ed6..8ae63b001c4cf2 100644 --- a/homeassistant/components/flux_led/util.py +++ b/homeassistant/components/flux_led/util.py @@ -12,8 +12,7 @@ def _hass_color_modes(device: AIOWifiLedBulb) -> set[str]: - color_modes = device.color_modes - if not color_modes: + if not (color_modes := device.color_modes): return {ColorMode.ONOFF} return {_flux_color_mode_to_hass(mode, color_modes) for mode in color_modes} diff --git a/homeassistant/components/fritzbox/climate.py b/homeassistant/components/fritzbox/climate.py index d5a81fdef1a3d3..bf5b68b6008538 100644 --- a/homeassistant/components/fritzbox/climate.py +++ b/homeassistant/components/fritzbox/climate.py @@ -135,11 +135,9 @@ def target_temperature(self) -> float: async def async_set_temperature(self, **kwargs: Any) -> None: """Set new target temperature.""" - target_temp = kwargs.get(ATTR_TEMPERATURE) - hvac_mode = kwargs.get(ATTR_HVAC_MODE) - if hvac_mode == HVACMode.OFF: + if (hvac_mode := kwargs.get(ATTR_HVAC_MODE)) == HVACMode.OFF: await self.async_set_hvac_mode(hvac_mode) - elif target_temp is not None: + elif (target_temp := kwargs.get(ATTR_TEMPERATURE)) is not None: await self.hass.async_add_executor_job( self.data.set_target_temperature, target_temp ) diff --git a/homeassistant/components/fujitsu_fglair/__init__.py b/homeassistant/components/fujitsu_fglair/__init__.py index f25e01bcd1172d..b0a89c970b4a38 100644 --- a/homeassistant/components/fujitsu_fglair/__init__.py +++ b/homeassistant/components/fujitsu_fglair/__init__.py @@ -59,8 +59,7 @@ async def async_migrate_entry(hass: HomeAssistant, entry: FGLairConfigEntry) -> if entry.version == 1: new_data = {**entry.data} if entry.minor_version < 2: - is_europe = new_data.get(CONF_EUROPE, False) - if is_europe: + if new_data.get(CONF_EUROPE, False): new_data[CONF_REGION] = REGION_EU else: new_data[CONF_REGION] = REGION_DEFAULT diff --git a/homeassistant/components/generic_hygrostat/humidifier.py b/homeassistant/components/generic_hygrostat/humidifier.py index 69c4fb3cdf40ef..bc2fc49ed531f7 100644 --- a/homeassistant/components/generic_hygrostat/humidifier.py +++ b/homeassistant/components/generic_hygrostat/humidifier.py @@ -400,8 +400,7 @@ async def _async_sensor_event( self, event: Event[EventStateChangedData] | Event[EventStateReportedData] ) -> None: """Handle ambient humidity changes.""" - new_state = event.data["new_state"] - if new_state is None: + if (new_state := event.data["new_state"]) is None: return await self._async_sensor_update(new_state) diff --git a/homeassistant/components/google/calendar.py b/homeassistant/components/google/calendar.py index 045e0e31b468c5..d9bf6796286db5 100644 --- a/homeassistant/components/google/calendar.py +++ b/homeassistant/components/google/calendar.py @@ -130,8 +130,7 @@ def _get_entity_descriptions( key = "" else: key = calendar_id - entity_enabled = data.get(CONF_TRACK, True) - if not entity_enabled: + if not (entity_enabled := data.get(CONF_TRACK, True)): _LOGGER.warning( "The 'track' option in google_calendars.yaml has been deprecated." " The setting has been imported to the UI, and should now be" diff --git a/homeassistant/components/google_cloud/tts.py b/homeassistant/components/google_cloud/tts.py index c3a8254ad90b5a..0bdbda34dbe101 100644 --- a/homeassistant/components/google_cloud/tts.py +++ b/homeassistant/components/google_cloud/tts.py @@ -178,8 +178,7 @@ async def _async_get_tts_audio( gender: texttospeech.SsmlVoiceGender | None = texttospeech.SsmlVoiceGender[ options[CONF_GENDER] ] # type: ignore[misc] - voice = options[CONF_VOICE] - if voice: + if voice := options[CONF_VOICE]: gender = None if not voice.startswith(language): language = voice[:5] diff --git a/homeassistant/components/hassio/coordinator.py b/homeassistant/components/hassio/coordinator.py index cb1dda8aeedc3c..c95374e5cb90a9 100644 --- a/homeassistant/components/hassio/coordinator.py +++ b/homeassistant/components/hassio/coordinator.py @@ -334,9 +334,8 @@ async def _async_update_data(self) -> dict[str, Any]: addons_info = get_addons_info(self.hass) or {} addons_stats = get_addons_stats(self.hass) addons_changelogs = get_addons_changelogs(self.hass) - store_data = get_store(self.hass) - if store_data: + if store_data := get_store(self.hass): repositories = { repo.slug: repo.name for repo in StoreInfo.from_dict(store_data).repositories diff --git a/homeassistant/components/hive/climate.py b/homeassistant/components/hive/climate.py index c76379cf940c28..d0ed6acf07f719 100644 --- a/homeassistant/components/hive/climate.py +++ b/homeassistant/components/hive/climate.py @@ -63,8 +63,7 @@ async def async_setup_entry( """Set up Hive thermostat based on a config entry.""" hive = hass.data[DOMAIN][entry.entry_id] - devices = hive.session.deviceList.get("climate") - if devices: + if devices := hive.session.deviceList.get("climate"): async_add_entities((HiveClimateEntity(hive, dev) for dev in devices), True) platform = entity_platform.async_get_current_platform() diff --git a/homeassistant/components/hive/light.py b/homeassistant/components/hive/light.py index b510569eb47f36..3e826f1e4ad09f 100644 --- a/homeassistant/components/hive/light.py +++ b/homeassistant/components/hive/light.py @@ -34,8 +34,7 @@ async def async_setup_entry( """Set up Hive thermostat based on a config entry.""" hive: Hive = hass.data[DOMAIN][entry.entry_id] - devices = hive.session.deviceList.get("light") - if not devices: + if not (devices := hive.session.deviceList.get("light")): return async_add_entities((HiveDeviceLight(hive, dev) for dev in devices), True) diff --git a/homeassistant/components/hive/sensor.py b/homeassistant/components/hive/sensor.py index 00a2116e26840d..cd5b0f7c23dd99 100644 --- a/homeassistant/components/hive/sensor.py +++ b/homeassistant/components/hive/sensor.py @@ -93,8 +93,7 @@ async def async_setup_entry( ) -> None: """Set up Hive thermostat based on a config entry.""" hive = hass.data[DOMAIN][entry.entry_id] - devices = hive.session.deviceList.get("sensor") - if not devices: + if not (devices := hive.session.deviceList.get("sensor")): return async_add_entities( ( diff --git a/homeassistant/components/hive/switch.py b/homeassistant/components/hive/switch.py index 1421616db57e7e..96c6f30d6d180b 100644 --- a/homeassistant/components/hive/switch.py +++ b/homeassistant/components/hive/switch.py @@ -38,8 +38,7 @@ async def async_setup_entry( """Set up Hive thermostat based on a config entry.""" hive = hass.data[DOMAIN][entry.entry_id] - devices = hive.session.deviceList.get("switch") - if not devices: + if not (devices := hive.session.deviceList.get("switch")): return async_add_entities( ( diff --git a/homeassistant/components/hive/water_heater.py b/homeassistant/components/hive/water_heater.py index b038739d2add2c..960ea1de9f1965 100644 --- a/homeassistant/components/hive/water_heater.py +++ b/homeassistant/components/hive/water_heater.py @@ -50,8 +50,7 @@ async def async_setup_entry( """Set up Hive thermostat based on a config entry.""" hive = hass.data[DOMAIN][entry.entry_id] - devices = hive.session.deviceList.get("water_heater") - if devices: + if devices := hive.session.deviceList.get("water_heater"): async_add_entities((HiveWaterHeater(hive, dev) for dev in devices), True) platform = entity_platform.async_get_current_platform() diff --git a/homeassistant/components/home_connect/time.py b/homeassistant/components/home_connect/time.py index c1f125cd2f76a5..0734c5fed92987 100644 --- a/homeassistant/components/home_connect/time.py +++ b/homeassistant/components/home_connect/time.py @@ -94,13 +94,11 @@ async def async_set_value(self, value: time) -> None: async def async_update(self) -> None: """Update the Time setting status.""" - data = self.device.appliance.status.get(self.bsh_key) - if data is None: + if (data := self.device.appliance.status.get(self.bsh_key)) is None: _LOGGER.error("No value for %s", self.bsh_key) self._attr_native_value = None return - seconds = data.get(ATTR_VALUE, None) - if seconds is not None: + if (seconds := data.get(ATTR_VALUE, None)) is not None: self._attr_native_value = seconds_to_time(seconds) else: self._attr_native_value = None diff --git a/homeassistant/components/homeassistant/scene.py b/homeassistant/components/homeassistant/scene.py index aec9b9cd06b6f7..3db550b614c861 100644 --- a/homeassistant/components/homeassistant/scene.py +++ b/homeassistant/components/homeassistant/scene.py @@ -275,8 +275,7 @@ async def delete_service(call: ServiceCall) -> None: entity_ids = await async_extract_entity_ids(hass, call) for entity_id in entity_ids: - scene = platform.entities.get(entity_id) - if scene is None: + if (scene := platform.entities.get(entity_id)) is None: raise ServiceValidationError( translation_domain=SCENE_DOMAIN, translation_key="entity_not_scene", diff --git a/homeassistant/components/homeassistant/triggers/numeric_state.py b/homeassistant/components/homeassistant/triggers/numeric_state.py index dac250792ea31a..a8c47acfb37703 100644 --- a/homeassistant/components/homeassistant/triggers/numeric_state.py +++ b/homeassistant/components/homeassistant/triggers/numeric_state.py @@ -157,9 +157,8 @@ def state_automation_listener(event: Event[EventStateChangedData]) -> None: """Listen for state changes and calls action.""" entity_id = event.data["entity_id"] from_s = event.data["old_state"] - to_s = event.data["new_state"] - if to_s is None: + if (to_s := event.data["new_state"]) is None: return @callback diff --git a/homeassistant/components/homekit/type_covers.py b/homeassistant/components/homekit/type_covers.py index 6752633f3d268e..2773b7f81ed0f3 100644 --- a/homeassistant/components/homekit/type_covers.py +++ b/homeassistant/components/homekit/type_covers.py @@ -433,8 +433,7 @@ def async_update_state(self, new_state: State) -> None: """Update cover position after state changed.""" position_mapping = {CoverState.OPEN: 100, CoverState.CLOSED: 0} _state: CoverState = new_state.state # type: ignore[assignment] - hk_position = position_mapping.get(_state) - if hk_position is not None: + if (hk_position := position_mapping.get(_state)) is not None: is_moving = _state in MOVING_STATES if self.char_current_position.value != hk_position: diff --git a/homeassistant/components/huum/climate.py b/homeassistant/components/huum/climate.py index 7e0e4ce5ef13f6..30c5e172806186 100644 --- a/homeassistant/components/huum/climate.py +++ b/homeassistant/components/huum/climate.py @@ -103,8 +103,7 @@ async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None: async def async_set_temperature(self, **kwargs: Any) -> None: """Set new target temperature.""" - temperature = kwargs.get(ATTR_TEMPERATURE) - if temperature is None: + if (temperature := kwargs.get(ATTR_TEMPERATURE)) is None: return self._target_temperature = temperature diff --git a/homeassistant/components/image/media_source.py b/homeassistant/components/image/media_source.py index 8d06ec3807f891..9a52708a30e76a 100644 --- a/homeassistant/components/image/media_source.py +++ b/homeassistant/components/image/media_source.py @@ -35,9 +35,7 @@ def __init__(self, hass: HomeAssistant) -> None: async def async_resolve_media(self, item: MediaSourceItem) -> PlayMedia: """Resolve media to a url.""" - image = self.hass.data[DATA_COMPONENT].get_entity(item.identifier) - - if not image: + if not (image := self.hass.data[DATA_COMPONENT].get_entity(item.identifier)): raise Unresolvable(f"Could not resolve media item: {item.identifier}") return PlayMedia( diff --git a/homeassistant/components/insteon/config_flow.py b/homeassistant/components/insteon/config_flow.py index 143a9e2a5e211f..f04d3704fac964 100644 --- a/homeassistant/components/insteon/config_flow.py +++ b/homeassistant/components/insteon/config_flow.py @@ -74,8 +74,7 @@ async def async_step_plm( return self.async_create_entry(title="", data=user_input) errors["base"] = "cannot_connect" schema_defaults = user_input if user_input is not None else {} - ports = await async_get_usb_ports(self.hass) - if not ports: + if not (ports := await async_get_usb_ports(self.hass)): return await self.async_step_plm_manually() ports[PLM_MANUAL] = "Enter manually" data_schema = build_plm_schema(ports, **schema_defaults) diff --git a/homeassistant/components/integration/sensor.py b/homeassistant/components/integration/sensor.py index a053e5cea5cea0..394d71fa912c92 100644 --- a/homeassistant/components/integration/sensor.py +++ b/homeassistant/components/integration/sensor.py @@ -257,8 +257,7 @@ async def async_setup_entry( else: max_sub_interval = None - round_digits = config_entry.options.get(CONF_ROUND_DIGITS) - if round_digits: + if round_digits := config_entry.options.get(CONF_ROUND_DIGITS): round_digits = int(round_digits) integral = IntegrationSensor( diff --git a/homeassistant/components/intent/timers.py b/homeassistant/components/intent/timers.py index 84b96492241cc2..c147a678aebc1a 100644 --- a/homeassistant/components/intent/timers.py +++ b/homeassistant/components/intent/timers.py @@ -324,8 +324,7 @@ async def _wait_for_timer( def cancel_timer(self, timer_id: str) -> None: """Cancel a timer.""" - timer = self.timers.pop(timer_id, None) - if timer is None: + if (timer := self.timers.pop(timer_id, None)) is None: raise TimerNotFoundError if timer.is_active: @@ -346,8 +345,7 @@ def cancel_timer(self, timer_id: str) -> None: def add_time(self, timer_id: str, seconds: int) -> None: """Add time to a timer.""" - timer = self.timers.get(timer_id) - if timer is None: + if (timer := self.timers.get(timer_id)) is None: raise TimerNotFoundError if seconds == 0: @@ -389,8 +387,7 @@ def remove_time(self, timer_id: str, seconds: int) -> None: def pause_timer(self, timer_id: str) -> None: """Pauses a timer.""" - timer = self.timers.get(timer_id) - if timer is None: + if (timer := self.timers.get(timer_id)) is None: raise TimerNotFoundError if not timer.is_active: @@ -413,8 +410,7 @@ def pause_timer(self, timer_id: str) -> None: def unpause_timer(self, timer_id: str) -> None: """Unpause a timer.""" - timer = self.timers.get(timer_id) - if timer is None: + if (timer := self.timers.get(timer_id)) is None: raise TimerNotFoundError if timer.is_active: @@ -717,8 +713,7 @@ def _find_timers( return matching_timers area_registry = ar.async_get(hass) - area = area_registry.async_get_area(device.area_id) - if area is None: + if (area := area_registry.async_get_area(device.area_id)) is None: return matching_timers def area_floor_sort(timer: TimerInfo) -> int: diff --git a/homeassistant/components/ipma/weather.py b/homeassistant/components/ipma/weather.py index 855587eee2eb12..ca231f4fb3bd99 100644 --- a/homeassistant/components/ipma/weather.py +++ b/homeassistant/components/ipma/weather.py @@ -138,9 +138,7 @@ def _condition_conversion(self, identifier, forecast_dt): @property def condition(self): """Return the current condition which is only available on the hourly forecast data.""" - forecast = self._hourly_forecast - - if not forecast: + if not (forecast := self._hourly_forecast): return None return self._condition_conversion(forecast[0].weather_type.id, None) diff --git a/homeassistant/components/iskra/entity.py b/homeassistant/components/iskra/entity.py index f1c01d3eaa4030..72bb344a5939b8 100644 --- a/homeassistant/components/iskra/entity.py +++ b/homeassistant/components/iskra/entity.py @@ -16,9 +16,8 @@ def __init__(self, coordinator: IskraDataUpdateCoordinator) -> None: """Initialize the Iskra device.""" super().__init__(coordinator) self.device = coordinator.device - gateway = self.device.parent_device - if gateway is not None: + if (gateway := self.device.parent_device) is not None: self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, self.device.serial)}, manufacturer=MANUFACTURER, diff --git a/homeassistant/components/knx/__init__.py b/homeassistant/components/knx/__init__.py index ea654c358e749f..913c6d20f62938 100644 --- a/homeassistant/components/knx/__init__.py +++ b/homeassistant/components/knx/__init__.py @@ -145,8 +145,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Load a config entry.""" # `_KNX_YAML_CONFIG` is only set in async_setup. # It's None when reloading the integration or no `knx` key in configuration.yaml - config = hass.data.pop(_KNX_YAML_CONFIG, None) - if config is None: + if (config := hass.data.pop(_KNX_YAML_CONFIG, None)) is None: _conf = await async_integration_yaml_config(hass, DOMAIN) if not _conf or DOMAIN not in _conf: # generate defaults @@ -185,8 +184,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unloading the KNX platforms.""" - knx_module = hass.data.get(KNX_MODULE_KEY) - if not knx_module: + if not (knx_module := hass.data.get(KNX_MODULE_KEY)): # if not loaded directly return return True diff --git a/homeassistant/components/lg_thinq/mqtt.py b/homeassistant/components/lg_thinq/mqtt.py index 8759869aad30b8..44cb71a7fa6d4e 100644 --- a/homeassistant/components/lg_thinq/mqtt.py +++ b/homeassistant/components/lg_thinq/mqtt.py @@ -172,8 +172,7 @@ async def async_handle_device_event(self, message: dict) -> None: if message["deviceType"] == DeviceType.WASHTOWER else message["deviceId"] ) - coordinator = self.coordinators.get(unique_id) - if coordinator is None: + if (coordinator := self.coordinators.get(unique_id)) is None: _LOGGER.error("Failed to handle device event: No device") return diff --git a/homeassistant/components/lifx/manager.py b/homeassistant/components/lifx/manager.py index 590d133c4a4fa2..767215482bb813 100644 --- a/homeassistant/components/lifx/manager.py +++ b/homeassistant/components/lifx/manager.py @@ -409,8 +409,7 @@ async def start_effect( await self.effects_conductor.start(effect, bulbs) elif service == SERVICE_EFFECT_SKY: - palette = kwargs.get(ATTR_PALETTE) - if palette is not None: + if (palette := kwargs.get(ATTR_PALETTE)) is not None: theme = Theme() for hsbk in palette: theme.add_hsbk(hsbk[0], hsbk[1], hsbk[2], hsbk[3]) diff --git a/homeassistant/components/linkplay/media_player.py b/homeassistant/components/linkplay/media_player.py index 456fbf23289219..cd630d1e0a166c 100644 --- a/homeassistant/components/linkplay/media_player.py +++ b/homeassistant/components/linkplay/media_player.py @@ -272,13 +272,11 @@ async def async_join_players(self, group_members: list[str]) -> None: """Join `group_members` as a player group with the current player.""" controller: LinkPlayController = self.hass.data[DOMAIN][CONTROLLER_KEY] - multiroom = self._bridge.multiroom - if multiroom is None: + if (multiroom := self._bridge.multiroom) is None: multiroom = LinkPlayMultiroom(self._bridge) for group_member in group_members: - bridge = self._get_linkplay_bridge(group_member) - if bridge: + if bridge := self._get_linkplay_bridge(group_member): await multiroom.add_follower(bridge) await controller.discover_multirooms() @@ -315,8 +313,7 @@ def _get_linkplay_bridge(self, entity_id: str) -> LinkPlayBridge: @property def group_members(self) -> list[str]: """List of players which are grouped together.""" - multiroom = self._bridge.multiroom - if multiroom is not None: + if (multiroom := self._bridge.multiroom) is not None: return [multiroom.leader.device.uuid] + [ follower.device.uuid for follower in multiroom.followers ] @@ -328,8 +325,7 @@ async def async_unjoin_player(self) -> None: """Remove this player from any group.""" controller: LinkPlayController = self.hass.data[DOMAIN][CONTROLLER_KEY] - multiroom = self._bridge.multiroom - if multiroom is not None: + if (multiroom := self._bridge.multiroom) is not None: await multiroom.remove_follower(self._bridge) await controller.discover_multirooms() diff --git a/homeassistant/components/lutron_caseta/util.py b/homeassistant/components/lutron_caseta/util.py index d4f0a9083fe09e..919a21450d8bab 100644 --- a/homeassistant/components/lutron_caseta/util.py +++ b/homeassistant/components/lutron_caseta/util.py @@ -22,8 +22,7 @@ def _construct_area_name_from_id( ) -> str: """Recursively construct the full area name including parent(s).""" area = areas[area_id] - parent_area_id = area["parent_id"] - if parent_area_id is None: + if (parent_area_id := area["parent_id"]) is None: # This is the root area, return last area return " ".join(labels) diff --git a/homeassistant/components/madvr/config_flow.py b/homeassistant/components/madvr/config_flow.py index 60f7b8fc481574..7ccface25dc0c6 100644 --- a/homeassistant/components/madvr/config_flow.py +++ b/homeassistant/components/madvr/config_flow.py @@ -122,8 +122,7 @@ async def test_connection(hass: HomeAssistant, host: str, port: int) -> str: await asyncio.sleep(RETRY_INTERVAL) retry_time -= 1 - mac_address = madvr_client.mac_address - if mac_address: + if mac_address := madvr_client.mac_address: _LOGGER.debug("Connected to madVR with MAC: %s", mac_address) # close this connection because this client object will not be reused await close_test_connection(madvr_client) diff --git a/homeassistant/components/mastodon/notify.py b/homeassistant/components/mastodon/notify.py index 7878fc665a177d..7c51412d81a12f 100644 --- a/homeassistant/components/mastodon/notify.py +++ b/homeassistant/components/mastodon/notify.py @@ -125,8 +125,7 @@ def send_message(self, message: str = "", **kwargs: Any) -> None: content_warning = None if data: - media = data.get(ATTR_MEDIA) - if media: + if media := data.get(ATTR_MEDIA): if not self.hass.config.is_allowed_path(media): LOGGER.warning("'%s' is not a whitelisted directory", media) return diff --git a/homeassistant/components/matter/__init__.py b/homeassistant/components/matter/__init__.py index e751387d7e8cc6..c007f446d15791 100644 --- a/homeassistant/components/matter/__init__.py +++ b/homeassistant/components/matter/__init__.py @@ -252,9 +252,7 @@ async def async_remove_config_entry_device( hass: HomeAssistant, config_entry: ConfigEntry, device_entry: dr.DeviceEntry ) -> bool: """Remove a config entry from a device.""" - node = get_node_from_device_entry(hass, device_entry) - - if node is None: + if (node := get_node_from_device_entry(hass, device_entry)) is None: # In case this was a bridge _remove_via_devices(hass, config_entry, device_entry) # Always allow users to remove orphan devices diff --git a/homeassistant/components/matter/helpers.py b/homeassistant/components/matter/helpers.py index abab258f550f15..fd66882d44ba46 100644 --- a/homeassistant/components/matter/helpers.py +++ b/homeassistant/components/matter/helpers.py @@ -76,8 +76,7 @@ def get_device_id( def node_from_ha_device_id(hass: HomeAssistant, ha_device_id: str) -> MatterNode | None: """Get node id from ha device id.""" dev_reg = dr.async_get(hass) - device = dev_reg.async_get(ha_device_id) - if device is None: + if (device := dev_reg.async_get(ha_device_id)) is None: raise MissingNode(f"Invalid device ID: {ha_device_id}") return get_node_from_device_entry(hass, device) diff --git a/homeassistant/components/mealie/calendar.py b/homeassistant/components/mealie/calendar.py index 4c11c639c793ff..c1d5d89c8c1679 100644 --- a/homeassistant/components/mealie/calendar.py +++ b/homeassistant/components/mealie/calendar.py @@ -57,8 +57,7 @@ def __init__( @property def event(self) -> CalendarEvent | None: """Return the next upcoming event.""" - mealplans = self.coordinator.data[self._entry_type] - if not mealplans: + if not (mealplans := self.coordinator.data[self._entry_type]): return None sorted_mealplans = sorted(mealplans, key=lambda x: x.mealplan_date) return _get_event_from_mealplan(sorted_mealplans[0]) diff --git a/homeassistant/components/modbus/validators.py b/homeassistant/components/modbus/validators.py index f8f1a7450eba8f..f521dde942a6d0 100644 --- a/homeassistant/components/modbus/validators.py +++ b/homeassistant/components/modbus/validators.py @@ -133,7 +133,7 @@ def struct_validator(config: dict[str, Any]) -> dict[str, Any]: name = config[CONF_NAME] data_type = config[CONF_DATA_TYPE] - if data_type == "int": + if data_type == "int": # pylint: disable=consider-using-assignment-expr data_type = config[CONF_DATA_TYPE] = DataType.INT16 count = config.get(CONF_COUNT) structure = config.get(CONF_STRUCTURE) diff --git a/homeassistant/components/mqtt/diagnostics.py b/homeassistant/components/mqtt/diagnostics.py index 8104c37574b2d4..eeb843de00d325 100644 --- a/homeassistant/components/mqtt/diagnostics.py +++ b/homeassistant/components/mqtt/diagnostics.py @@ -96,8 +96,7 @@ def _async_device_as_dict(hass: HomeAssistant, device: DeviceEntry) -> dict[str, ) def _state_dict(entity_entry: er.RegistryEntry) -> dict[str, Any] | None: - state = hass.states.get(entity_entry.entity_id) - if not state: + if not (state := hass.states.get(entity_entry.entity_id)): return None state_dict = dict(state.as_dict()) diff --git a/homeassistant/components/mqtt_statestream/__init__.py b/homeassistant/components/mqtt_statestream/__init__.py index 3a0953a0158422..de0ea39338e8fe 100644 --- a/homeassistant/components/mqtt_statestream/__init__.py +++ b/homeassistant/components/mqtt_statestream/__init__.py @@ -93,8 +93,7 @@ def _ha_started(hass: HomeAssistant) -> None: @callback def _event_filter(event_data: EventStateChangedData) -> bool: entity_id = event_data["entity_id"] - new_state = event_data["new_state"] - if new_state is None: + if event_data["new_state"] is None: return False if not publish_filter(entity_id): return False diff --git a/homeassistant/components/nasweb/__init__.py b/homeassistant/components/nasweb/__init__.py index 1992cc41c75a7c..07ef451a9d32a0 100644 --- a/homeassistant/components/nasweb/__init__.py +++ b/homeassistant/components/nasweb/__init__.py @@ -51,8 +51,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: NASwebConfigEntry) -> bo translation_key="config_entry_error_internal_error", translation_placeholders={"support_email": SUPPORT_EMAIL}, ) - webio_serial = webio_api.get_serial_number() - if webio_serial is None: + if (webio_serial := webio_api.get_serial_number()) is None: _LOGGER.error("[%s] Serial number not available", entry.data[CONF_HOST]) raise ConfigEntryError( translation_key="config_entry_error_internal_error", @@ -113,8 +112,7 @@ async def async_unload_entry(hass: HomeAssistant, entry: NASwebConfigEntry) -> b if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS): nasweb_data = hass.data[DATA_NASWEB] coordinator = entry.runtime_data - serial = entry.unique_id - if serial is not None: + if (serial := entry.unique_id) is not None: nasweb_data.notify_coordinator.remove_coordinator(serial) if nasweb_data.can_be_deinitialized(): nasweb_data.deinitialize(hass) diff --git a/homeassistant/components/nasweb/config_flow.py b/homeassistant/components/nasweb/config_flow.py index 3a9ad3f7d498e3..f7b48e1bca3828 100644 --- a/homeassistant/components/nasweb/config_flow.py +++ b/homeassistant/components/nasweb/config_flow.py @@ -49,8 +49,7 @@ async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> dict[str, nasweb_data = NASwebData() nasweb_data.initialize(hass) try: - webio_serial = webio_api.get_serial_number() - if webio_serial is None: + if (webio_serial := webio_api.get_serial_number()) is None: raise MissingNASwebData("Device serial number is not available") coordinator = NASwebCoordinator(hass, webio_api) diff --git a/homeassistant/components/nextbus/sensor.py b/homeassistant/components/nextbus/sensor.py index 554814fe2db11c..fc661e48c44e8b 100644 --- a/homeassistant/components/nextbus/sensor.py +++ b/homeassistant/components/nextbus/sensor.py @@ -121,11 +121,8 @@ def _handle_coordinator_update(self) -> None: } ) - # Chain all predictions together - predictions = results["values"] - # Short circuit if we don't have any actual bus predictions - if not predictions: + if not (predictions := results["values"]): self._log_debug("No upcoming predictions available") self._attr_native_value = None self._attr_extra_state_attributes["upcoming"] = "No upcoming predictions" diff --git a/homeassistant/components/ondilo_ico/coordinator.py b/homeassistant/components/ondilo_ico/coordinator.py index bc092ad0b9a886..32752e97a49ba1 100644 --- a/homeassistant/components/ondilo_ico/coordinator.py +++ b/homeassistant/components/ondilo_ico/coordinator.py @@ -54,8 +54,7 @@ def _update_data(self) -> dict[str, OndiloIcoData]: for pool in pools: pool_id = pool["id"] try: - ico = self.api.get_ICO_details(pool_id) - if not ico: + if not (ico := self.api.get_ICO_details(pool_id)): _LOGGER.debug( "The pool id %s does not have any ICO attached", pool_id ) diff --git a/homeassistant/components/onkyo/config_flow.py b/homeassistant/components/onkyo/config_flow.py index a8ced6fae640c4..18d7f12b07678e 100644 --- a/homeassistant/components/onkyo/config_flow.py +++ b/homeassistant/components/onkyo/config_flow.py @@ -226,8 +226,7 @@ async def async_step_configure_receiver( _LOGGER.debug("Configuring receiver, info: %s", self._receiver_info) - suggested_values = user_input - if suggested_values is None: + if (suggested_values := user_input) is None: if entry_options is None: suggested_values = { OPTION_VOLUME_RESOLUTION: OPTION_VOLUME_RESOLUTION_DEFAULT, diff --git a/homeassistant/components/onkyo/media_player.py b/homeassistant/components/onkyo/media_player.py index 24d63c0d9e4bfe..7ba64d0126d41a 100644 --- a/homeassistant/components/onkyo/media_player.py +++ b/homeassistant/components/onkyo/media_player.py @@ -295,8 +295,7 @@ def connect_callback(receiver: Receiver) -> None: def update_callback(receiver: Receiver, message: tuple[str, str, Any]) -> None: zone, _, value = message - entity = entities.get(zone) - if entity is not None: + if (entity := entities.get(zone)) is not None: if entity.enabled: entity.process_update(message) elif zone in ZONES and value != "N/A": diff --git a/homeassistant/components/openweathermap/__init__.py b/homeassistant/components/openweathermap/__init__.py index 33cd23c4f6c229..c51407c4991d9f 100644 --- a/homeassistant/components/openweathermap/__init__.py +++ b/homeassistant/components/openweathermap/__init__.py @@ -46,9 +46,8 @@ async def async_setup_entry( latitude = entry.data.get(CONF_LATITUDE, hass.config.latitude) longitude = entry.data.get(CONF_LONGITUDE, hass.config.longitude) language = entry.options[CONF_LANGUAGE] - mode = entry.options[CONF_MODE] - if mode == OWM_MODE_V25: + if (mode := entry.options[CONF_MODE]) == OWM_MODE_V25: async_create_issue(hass, entry.entry_id) else: async_delete_issue(hass, entry.entry_id) diff --git a/homeassistant/components/osoenergy/__init__.py b/homeassistant/components/osoenergy/__init__.py index ca6d52941f794a..6b8403259e6e1b 100644 --- a/homeassistant/components/osoenergy/__init__.py +++ b/homeassistant/components/osoenergy/__init__.py @@ -45,11 +45,11 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: hass.data[DOMAIN][entry.entry_id] = osoenergy - platforms = set() - for ha_type, oso_type in PLATFORM_LOOKUP.items(): - device_list = devices.get(oso_type, []) - if device_list: - platforms.add(ha_type) + platforms = { + ha_type + for ha_type, oso_type in PLATFORM_LOOKUP.items() + if devices.get(oso_type) + } if platforms: await hass.config_entries.async_forward_entry_setups(entry, platforms) return True diff --git a/homeassistant/components/osoenergy/water_heater.py b/homeassistant/components/osoenergy/water_heater.py index ff117d6577dc1d..5bd39bac2eb03a 100644 --- a/homeassistant/components/osoenergy/water_heater.py +++ b/homeassistant/components/osoenergy/water_heater.py @@ -183,8 +183,7 @@ def available(self) -> bool: @property def current_operation(self) -> str: """Return current operation.""" - status = self.entity_data.current_operation - if status == "off": + if self.entity_data.current_operation == "off": return STATE_OFF optimization_mode = self.entity_data.optimization_mode.lower() diff --git a/homeassistant/components/overkiz/climate/atlantic_pass_apc_zone_control_zone.py b/homeassistant/components/overkiz/climate/atlantic_pass_apc_zone_control_zone.py index 5ba9dabe03897c..5f8cc17fcdb7a2 100644 --- a/homeassistant/components/overkiz/climate/atlantic_pass_apc_zone_control_zone.py +++ b/homeassistant/components/overkiz/climate/atlantic_pass_apc_zone_control_zone.py @@ -369,9 +369,8 @@ async def async_set_temperature(self, **kwargs: Any) -> None: target_temperature = kwargs.get(ATTR_TEMPERATURE) target_temp_low = kwargs.get(ATTR_TARGET_TEMP_LOW) target_temp_high = kwargs.get(ATTR_TARGET_TEMP_HIGH) - hvac_mode = self.hvac_mode - if hvac_mode == HVACMode.HEAT_COOL: + if (hvac_mode := self.hvac_mode) == HVACMode.HEAT_COOL: if target_temp_low is not None: await self.executor.async_execute_command( OverkizCommand.SET_HEATING_TARGET_TEMPERATURE, diff --git a/homeassistant/components/prometheus/__init__.py b/homeassistant/components/prometheus/__init__.py index c243bf90dc0fff..2b0169a8c71f30 100644 --- a/homeassistant/components/prometheus/__init__.py +++ b/homeassistant/components/prometheus/__init__.py @@ -796,9 +796,7 @@ def _handle_update(self, state: State) -> None: metric.labels(**self._labels(state)).set(value) def _handle_alarm_control_panel(self, state: State) -> None: - current_state = state.state - - if current_state: + if current_state := state.state: metric = self._metric( "alarm_control_panel_state", prometheus_client.Gauge, diff --git a/homeassistant/components/python_script/__init__.py b/homeassistant/components/python_script/__init__.py index 70e9c5b0d29a78..76040bbe985534 100644 --- a/homeassistant/components/python_script/__init__.py +++ b/homeassistant/components/python_script/__init__.py @@ -174,8 +174,7 @@ def guarded_inplacevar(op: str, target: Any, operand: Any) -> Any: """ if not isinstance(target, (list, Number, str)): raise ScriptError(f"The {op!r} operation is not allowed on a {type(target)}") - op_fun = IOPERATOR_TO_OPERATOR.get(op) - if not op_fun: + if not (op_fun := IOPERATOR_TO_OPERATOR.get(op)): raise ScriptError(f"The {op!r} operation is not allowed") return op_fun(target, operand) diff --git a/homeassistant/components/rainbird/calendar.py b/homeassistant/components/rainbird/calendar.py index 160fe70c61e97f..4b9add57592fff 100644 --- a/homeassistant/components/rainbird/calendar.py +++ b/homeassistant/components/rainbird/calendar.py @@ -69,8 +69,7 @@ def __init__( @property def event(self) -> CalendarEvent | None: """Return the next upcoming event.""" - schedule = self.coordinator.data - if not schedule: + if not (schedule := self.coordinator.data): return None cursor = schedule.timeline_tz(dt_util.get_default_time_zone()).active_after( dt_util.now() @@ -89,8 +88,7 @@ async def async_get_events( self, hass: HomeAssistant, start_date: datetime, end_date: datetime ) -> list[CalendarEvent]: """Get all events in a specific time frame.""" - schedule = self.coordinator.data - if not schedule: + if not (schedule := self.coordinator.data): raise HomeAssistantError( "Unable to get events: No data from controller yet" ) diff --git a/homeassistant/components/rainforest_raven/config_flow.py b/homeassistant/components/rainforest_raven/config_flow.py index 72d258dc1d32a9..aaa374e953d98e 100644 --- a/homeassistant/components/rainforest_raven/config_flow.py +++ b/homeassistant/components/rainforest_raven/config_flow.py @@ -53,8 +53,7 @@ async def _validate_device(self, dev_path: str) -> None: RAVEnSerialDevice(dev_path) as raven_device, ): await raven_device.synchronize() - meters = await raven_device.get_meter_list() - if meters: + if meters := await raven_device.get_meter_list(): for meter in meters.meter_mac_ids or (): meter_info = await raven_device.get_meter_info(meter=meter) if meter_info and ( diff --git a/homeassistant/components/recorder/db_schema.py b/homeassistant/components/recorder/db_schema.py index 90ee9fca449cc5..4e688a3cddf927 100644 --- a/homeassistant/components/recorder/db_schema.py +++ b/homeassistant/components/recorder/db_schema.py @@ -498,9 +498,8 @@ def _last_updated_isotime(self) -> str | None: @staticmethod def from_event(event: Event[EventStateChangedData]) -> States: """Create object from a state_changed event.""" - state = event.data["new_state"] # None state means the state was removed from the state machine - if state is None: + if (state := event.data["new_state"]) is None: state_value = "" last_updated_ts = event.time_fired_timestamp last_changed_ts = None diff --git a/homeassistant/components/reolink/entity.py b/homeassistant/components/reolink/entity.py index dc2366e8f569dc..2dcc9757ec15c0 100644 --- a/homeassistant/components/reolink/entity.py +++ b/homeassistant/components/reolink/entity.py @@ -188,14 +188,12 @@ def register_callback(self, unique_id: str, cmd_id: int) -> None: async def async_added_to_hass(self) -> None: """Entity created.""" await super().async_added_to_hass() - cmd_key = self.entity_description.cmd_key - if cmd_key is not None: + if (cmd_key := self.entity_description.cmd_key) is not None: self._host.async_register_update_cmd(cmd_key, self._channel) async def async_will_remove_from_hass(self) -> None: """Entity removed.""" - cmd_key = self.entity_description.cmd_key - if cmd_key is not None: + if (cmd_key := self.entity_description.cmd_key) is not None: self._host.async_unregister_update_cmd(cmd_key, self._channel) await super().async_will_remove_from_hass() diff --git a/homeassistant/components/ring/camera.py b/homeassistant/components/ring/camera.py index ccd91c163d6587..b597e647540499 100644 --- a/homeassistant/components/ring/camera.py +++ b/homeassistant/components/ring/camera.py @@ -123,8 +123,7 @@ def _handle_coordinator_update(self) -> None: self._device = self._get_coordinator_data().get_video_device( self._device.device_api_id ) - history_data = self._device.last_history - if history_data: + if history_data := self._device.last_history: self._last_event = history_data[0] # will call async_update to update the attributes and get the # video url from the api diff --git a/homeassistant/components/roborock/__init__.py b/homeassistant/components/roborock/__init__.py index d02dddece42f1a..68386419828a24 100644 --- a/homeassistant/components/roborock/__init__.py +++ b/homeassistant/components/roborock/__init__.py @@ -171,8 +171,7 @@ async def setup_device_v1( RoborockMqttClientV1, user_data, DeviceData(device, product_info.model) ) try: - networking = await mqtt_client.get_networking() - if networking is None: + if (networking := await mqtt_client.get_networking()) is None: # If the api does not return an error but does return None for # get_networking - then we need to go through cache checking. raise RoborockException("Networking request returned None.") # noqa: TRY301 diff --git a/homeassistant/components/sabnzbd/__init__.py b/homeassistant/components/sabnzbd/__init__.py index 2e3d6dd613cf55..d5dc150879666e 100644 --- a/homeassistant/components/sabnzbd/__init__.py +++ b/homeassistant/components/sabnzbd/__init__.py @@ -150,8 +150,7 @@ async def async_set_queue_speed( async def async_setup_entry(hass: HomeAssistant, entry: SabnzbdConfigEntry) -> bool: """Set up the SabNzbd Component.""" - sab_api = await get_client(hass, entry.data) - if not sab_api: + if not (sab_api := await get_client(hass, entry.data)): raise ConfigEntryNotReady coordinator = SabnzbdUpdateCoordinator(hass, entry, sab_api) diff --git a/homeassistant/components/sabnzbd/config_flow.py b/homeassistant/components/sabnzbd/config_flow.py index ce9b0a13b18dae..3930d38662fe79 100644 --- a/homeassistant/components/sabnzbd/config_flow.py +++ b/homeassistant/components/sabnzbd/config_flow.py @@ -60,8 +60,7 @@ async def async_step_user( errors = {} if user_input is not None: - sab_api = await get_client(self.hass, user_input) - if not sab_api: + if not await get_client(self.hass, user_input): errors["base"] = "cannot_connect" else: self._async_abort_entries_match( diff --git a/homeassistant/components/shelly/utils.py b/homeassistant/components/shelly/utils.py index df374624e3d70b..afc9d9be63aa5e 100644 --- a/homeassistant/components/shelly/utils.py +++ b/homeassistant/components/shelly/utils.py @@ -527,9 +527,7 @@ def is_rpc_thermostat_mode(ident: int, status: dict[str, Any]) -> bool: def get_virtual_component_ids(config: dict[str, Any], platform: str) -> list[str]: """Return a list of virtual component IDs for a platform.""" - component = VIRTUAL_COMPONENTS_MAP.get(platform) - - if not component: + if not (component := VIRTUAL_COMPONENTS_MAP.get(platform)): return [] ids: list[str] = [] diff --git a/homeassistant/components/smlight/config_flow.py b/homeassistant/components/smlight/config_flow.py index 92b543e04410ca..1c5d7ec6bcf5ac 100644 --- a/homeassistant/components/smlight/config_flow.py +++ b/homeassistant/components/smlight/config_flow.py @@ -92,9 +92,8 @@ async def async_step_zeroconf( self.context["title_placeholders"] = {CONF_NAME: node_name} self.client = Api2(self.host, session=async_get_clientsession(self.hass)) - mac = discovery_info.properties.get("mac") # fallback for legacy firmware - if mac is None: + if (mac := discovery_info.properties.get("mac")) is None: try: info = await self.client.get_info() except SmlightConnectionError: diff --git a/homeassistant/components/snapcast/media_player.py b/homeassistant/components/snapcast/media_player.py index 0ec27c1ad9c965..4745a643744dc9 100644 --- a/homeassistant/components/snapcast/media_player.py +++ b/homeassistant/components/snapcast/media_player.py @@ -366,8 +366,7 @@ async def async_set_latency(self, latency) -> None: async def async_join(self, master) -> None: """Join the group of the master player.""" entity_registry = er.async_get(self.hass) - master_entity = entity_registry.async_get(master) - if master_entity is None: + if (master_entity := entity_registry.async_get(master)) is None: raise ServiceValidationError(f"Master entity '{master}' not found.") # Validate master entity is a client diff --git a/homeassistant/components/solarlog/sensor.py b/homeassistant/components/solarlog/sensor.py index bcff5d57e1b506..715033d31f6449 100644 --- a/homeassistant/components/solarlog/sensor.py +++ b/homeassistant/components/solarlog/sensor.py @@ -286,9 +286,7 @@ async def async_setup_entry( for sensor in SOLARLOG_SENSOR_TYPES ] - device_data = coordinator.data.inverter_data - - if device_data: + if device_data := coordinator.data.inverter_data: entities.extend( SolarLogInverterSensor(coordinator, sensor, device_id) for device_id in device_data diff --git a/homeassistant/components/soma/sensor.py b/homeassistant/components/soma/sensor.py index 806886009f308e..3089dc84685cc4 100644 --- a/homeassistant/components/soma/sensor.py +++ b/homeassistant/components/soma/sensor.py @@ -44,8 +44,7 @@ def native_value(self): async def async_update(self) -> None: """Update the sensor with the latest data.""" response = await self.get_battery_level_from_api() - _battery = response.get("battery_percentage") - if _battery is None: + if (_battery := response.get("battery_percentage")) is None: # https://support.somasmarthome.com/hc/en-us/articles/360026064234-HTTP-API # battery_level response is expected to be min = 360, max 410 for # 0-100% levels above 410 are consider 100% and below 360, 0% as the diff --git a/homeassistant/components/sonos/speaker.py b/homeassistant/components/sonos/speaker.py index 32ff277d6782df..c204ae5a7acb6b 100644 --- a/homeassistant/components/sonos/speaker.py +++ b/homeassistant/components/sonos/speaker.py @@ -885,8 +885,7 @@ def _async_regroup(group: list[str]) -> None: sonos_group_entities = [] for uid in group: - speaker = self.data.discovered.get(uid) - if speaker: + if speaker := self.data.discovered.get(uid): self._group_members_missing.discard(uid) sonos_group.append(speaker) entity_id = cast( diff --git a/homeassistant/components/streamlabswater/config_flow.py b/homeassistant/components/streamlabswater/config_flow.py index e931a7cf3ba6d5..12931ff9585375 100644 --- a/homeassistant/components/streamlabswater/config_flow.py +++ b/homeassistant/components/streamlabswater/config_flow.py @@ -19,9 +19,8 @@ async def validate_input(hass: HomeAssistant, api_key: str) -> None: """Validate the user input allows us to connect.""" client = StreamlabsClient(api_key) response = await hass.async_add_executor_job(client.get_locations) - locations = response.get("locations") - if locations is None: + if response.get("locations") is None: raise CannotConnect diff --git a/homeassistant/components/swiss_public_transport/coordinator.py b/homeassistant/components/swiss_public_transport/coordinator.py index 59602e7b982e46..a36c80797e4e14 100644 --- a/homeassistant/components/swiss_public_transport/coordinator.py +++ b/homeassistant/components/swiss_public_transport/coordinator.py @@ -76,9 +76,7 @@ def __init__( def remaining_time(self, departure) -> timedelta | None: """Calculate the remaining time for the departure.""" - departure_datetime = dt_util.parse_datetime(departure) - - if departure_datetime: + if departure_datetime := dt_util.parse_datetime(departure): return departure_datetime - dt_util.as_local(dt_util.utcnow()) return None diff --git a/homeassistant/components/tami4/config_flow.py b/homeassistant/components/tami4/config_flow.py index 72b19470f450c9..2a282151b11df0 100644 --- a/homeassistant/components/tami4/config_flow.py +++ b/homeassistant/components/tami4/config_flow.py @@ -82,8 +82,7 @@ async def async_step_otp( _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: - device_name = api.device_metadata.name - if device_name is None: + if (device_name := api.device_metadata.name) is None: device_name = "Tami4" return self.async_create_entry( title=device_name, diff --git a/homeassistant/components/template/__init__.py b/homeassistant/components/template/__init__.py index 390a4a31bdb7db..622cce214794c0 100644 --- a/homeassistant/components/template/__init__.py +++ b/homeassistant/components/template/__init__.py @@ -118,10 +118,8 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: async def _process_config(hass: HomeAssistant, hass_config: ConfigType) -> None: """Process config.""" - coordinators = hass.data.pop(DATA_COORDINATORS, None) - # Remove old ones - if coordinators: + if coordinators := hass.data.pop(DATA_COORDINATORS, None): for coordinator in coordinators: coordinator.async_remove() diff --git a/homeassistant/components/tesla_fleet/select.py b/homeassistant/components/tesla_fleet/select.py index 515a0e7c2e76de..7c8b7af79278b3 100644 --- a/homeassistant/components/tesla_fleet/select.py +++ b/homeassistant/components/tesla_fleet/select.py @@ -136,8 +136,7 @@ def __init__( def _async_update_attrs(self) -> None: """Handle updated data from the coordinator.""" self._attr_available = self.entity_description.available_fn(self) - value = self._value - if value is None: + if (value := self._value) is None: self._attr_current_option = None else: self._attr_current_option = self._attr_options[value] @@ -181,8 +180,7 @@ def __init__( def _async_update_attrs(self) -> None: """Handle updated data from the coordinator.""" - value = self._value - if value is None: + if (value := self._value) is None: self._attr_current_option = None else: self._attr_current_option = self._attr_options[value] diff --git a/homeassistant/components/teslemetry/climate.py b/homeassistant/components/teslemetry/climate.py index 95b769a1c2d19c..4a42b0bffe2434 100644 --- a/homeassistant/components/teslemetry/climate.py +++ b/homeassistant/components/teslemetry/climate.py @@ -95,8 +95,7 @@ def __init__( def _async_update_attrs(self) -> None: """Update the attributes of the entity.""" - value = self.get("climate_state_is_climate_on") - if value: + if self.get("climate_state_is_climate_on"): self._attr_hvac_mode = HVACMode.HEAT_COOL else: self._attr_hvac_mode = HVACMode.OFF diff --git a/homeassistant/components/todo/__init__.py b/homeassistant/components/todo/__init__.py index e4bc549a16b35d..eecc4dbf17ff97 100644 --- a/homeassistant/components/todo/__init__.py +++ b/homeassistant/components/todo/__init__.py @@ -247,8 +247,7 @@ class TodoListEntity(Entity, cached_properties=CACHED_PROPERTIES_WITH_ATTR_): @property def state(self) -> int | None: """Return the entity state as the count of incomplete items.""" - items = self.todo_items - if items is None: + if (items := self.todo_items) is None: return None return sum([item.status == TodoItemStatus.NEEDS_ACTION for item in items]) diff --git a/homeassistant/components/tplink/entity.py b/homeassistant/components/tplink/entity.py index ef9e2ad5eeef0d..bd10ca04cf8e93 100644 --- a/homeassistant/components/tplink/entity.py +++ b/homeassistant/components/tplink/entity.py @@ -261,10 +261,9 @@ def _get_feature_unique_id( device: Device, entity_description: TPLinkFeatureEntityDescription ) -> str: """Return unique ID for the entity.""" - key = entity_description.key # The unique id for the state feature in the switch platform is the # device_id - if key == PRIMARY_STATE_ID: + if (key := entity_description.key) == PRIMARY_STATE_ID: return legacy_device_id(device) # Historically the legacy device emeter attributes which are now diff --git a/homeassistant/components/tplink_lte/notify.py b/homeassistant/components/tplink_lte/notify.py index 674f09efcd7f27..32a6ceec2c7bb3 100644 --- a/homeassistant/components/tplink_lte/notify.py +++ b/homeassistant/components/tplink_lte/notify.py @@ -41,7 +41,7 @@ async def async_send_message(self, message: str = "", **kwargs: Any) -> None: lte_data: LTEData = self.hass.data[DATA_KEY] modem_data = lte_data.get_modem_data(self.config) - if not modem_data: + if not (modem_data := lte_data.get_modem_data(self.config)): _LOGGER.error("No modem available") return diff --git a/homeassistant/components/tplink_omada/binary_sensor.py b/homeassistant/components/tplink_omada/binary_sensor.py index 73d5f54b8b3c56..c8b4ebda99cd9a 100644 --- a/homeassistant/components/tplink_omada/binary_sensor.py +++ b/homeassistant/components/tplink_omada/binary_sensor.py @@ -33,8 +33,7 @@ async def async_setup_entry( """Set up binary sensors.""" controller = config_entry.runtime_data - gateway_coordinator = controller.gateway_coordinator - if not gateway_coordinator: + if not (gateway_coordinator := controller.gateway_coordinator): return entities: list[OmadaDeviceEntity] = [] diff --git a/homeassistant/components/tplink_omada/switch.py b/homeassistant/components/tplink_omada/switch.py index f99d8aaedde1f4..162d580ce9d16d 100644 --- a/homeassistant/components/tplink_omada/switch.py +++ b/homeassistant/components/tplink_omada/switch.py @@ -69,8 +69,7 @@ async def async_setup_entry( if desc.exists_func(switch, port) ) - gateway_coordinator = controller.gateway_coordinator - if gateway_coordinator: + if gateway_coordinator := controller.gateway_coordinator: for gateway in gateway_coordinator.data.values(): entities.extend( OmadaDevicePortSwitchEntity[ diff --git a/homeassistant/components/trace/util.py b/homeassistant/components/trace/util.py index 73e65dd3998a49..30f8f29c0b1e31 100644 --- a/homeassistant/components/trace/util.py +++ b/homeassistant/components/trace/util.py @@ -69,8 +69,7 @@ async def async_list_traces( if not wanted_key: traces: list[dict[str, Any]] = [] for key in hass.data[DATA_TRACE]: - domain = key.split(".", 1)[0] - if domain == wanted_domain: + if key.split(".", 1)[0] == wanted_domain: traces.extend(_get_debug_traces(hass, key)) else: traces = _get_debug_traces(hass, wanted_key) diff --git a/homeassistant/components/tts/__init__.py b/homeassistant/components/tts/__init__.py index 972f14072fa018..79fd26f5b0066c 100644 --- a/homeassistant/components/tts/__init__.py +++ b/homeassistant/components/tts/__init__.py @@ -662,8 +662,7 @@ async def async_get_url_path( ) # Use a randomly generated token instead of exposing the filename - token = self.filename_to_token.get(filename) - if not token: + if not (token := self.filename_to_token.get(filename)): # Keep extension (.mp3, etc.) token = secrets.token_urlsafe(16) + os.path.splitext(filename)[1] @@ -930,8 +929,7 @@ async def async_read_tts(self, token: str) -> tuple[str | None, bytes]: This method is a coroutine. """ - filename = self.token_to_filename.get(token) - if not filename: + if not (filename := self.token_to_filename.get(token)): raise HomeAssistantError(f"{token} was not recognized!") if not (record := _RE_VOICE_FILE.match(filename.lower())) and not ( diff --git a/homeassistant/components/unifi_direct/device_tracker.py b/homeassistant/components/unifi_direct/device_tracker.py index d5e2e926114fef..414f51a4e96673 100644 --- a/homeassistant/components/unifi_direct/device_tracker.py +++ b/homeassistant/components/unifi_direct/device_tracker.py @@ -58,8 +58,7 @@ def scan_devices(self) -> list[str]: def get_device_name(self, device: str) -> str | None: """Return the name of the given device or None if we don't know.""" - client_info = self.clients.get(device) - if client_info: + if client_info := self.clients.get(device): return client_info.get("hostname") return None diff --git a/homeassistant/components/unifiprotect/data.py b/homeassistant/components/unifiprotect/data.py index baecc7f8323ac5..f43fd4c2204708 100644 --- a/homeassistant/components/unifiprotect/data.py +++ b/homeassistant/components/unifiprotect/data.py @@ -256,8 +256,7 @@ def _async_process_ws_message(self, message: WSSubscriptionMessage) -> None: self._async_remove_device(message.old_obj) return - model_type = new_obj.model - if model_type is ModelType.EVENT: + if (model_type := new_obj.model) is ModelType.EVENT: if TYPE_CHECKING: assert isinstance(new_obj, Event) if _LOGGER.isEnabledFor(logging.DEBUG): diff --git a/homeassistant/components/utility_meter/sensor.py b/homeassistant/components/utility_meter/sensor.py index af16a2aa867b29..4d8d82708e3d2d 100644 --- a/homeassistant/components/utility_meter/sensor.py +++ b/homeassistant/components/utility_meter/sensor.py @@ -483,7 +483,7 @@ def async_reading(self, event: Event[EventStateChangedData]) -> None: old_state = event.data["old_state"] new_state = event.data["new_state"] - if new_state is None: + if new_state is None: # pylint: disable=consider-using-assignment-expr return new_state_attributes: Mapping[str, Any] = new_state.attributes or {} diff --git a/homeassistant/components/verisure/lock.py b/homeassistant/components/verisure/lock.py index 87f5c53880e0ab..c3d2f08c27fcf8 100644 --- a/homeassistant/components/verisure/lock.py +++ b/homeassistant/components/verisure/lock.py @@ -128,14 +128,12 @@ def extra_state_attributes(self) -> dict[str, str]: async def async_unlock(self, **kwargs: Any) -> None: """Send unlock command.""" - code = kwargs.get(ATTR_CODE) - if code: + if code := kwargs.get(ATTR_CODE): await self.async_set_lock_state(code, LockState.UNLOCKED) async def async_lock(self, **kwargs: Any) -> None: """Send lock command.""" - code = kwargs.get(ATTR_CODE) - if code: + if code := kwargs.get(ATTR_CODE): await self.async_set_lock_state(code, LockState.LOCKED) async def async_set_lock_state(self, code: str, state: LockState) -> None: diff --git a/homeassistant/components/voip/assist_satellite.py b/homeassistant/components/voip/assist_satellite.py index 0100435d6dc8c3..d73249ef17b7dd 100644 --- a/homeassistant/components/voip/assist_satellite.py +++ b/homeassistant/components/voip/assist_satellite.py @@ -176,8 +176,7 @@ async def _run_pipeline(self) -> None: async def stt_stream(): while True: async with asyncio.timeout(self._audio_chunk_timeout): - chunk = await self._audio_queue.get() - if not chunk: + if not (chunk := await self._audio_queue.get()): break yield chunk diff --git a/homeassistant/components/wake_word/__init__.py b/homeassistant/components/wake_word/__init__.py index 8b3a5bbf33118d..44afdb8402da90 100644 --- a/homeassistant/components/wake_word/__init__.py +++ b/homeassistant/components/wake_word/__init__.py @@ -141,9 +141,7 @@ async def websocket_entity_info( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict ) -> None: """Get info about wake word entity.""" - entity = hass.data[DATA_COMPONENT].get_entity(msg["entity_id"]) - - if entity is None: + if (entity := hass.data[DATA_COMPONENT].get_entity(msg["entity_id"])) is None: connection.send_error( msg["id"], websocket_api.ERR_NOT_FOUND, "Entity not found" ) diff --git a/homeassistant/components/weatherkit/weather.py b/homeassistant/components/weatherkit/weather.py index 98816d520ba305..8fd822a1d6ca1e 100644 --- a/homeassistant/components/weatherkit/weather.py +++ b/homeassistant/components/weatherkit/weather.py @@ -240,8 +240,7 @@ def wind_bearing(self) -> float | None: @callback def _async_forecast_daily(self) -> list[Forecast] | None: """Return the daily forecast.""" - daily_forecast = self.data.get(ATTR_FORECAST_DAILY) - if not daily_forecast: + if not (daily_forecast := self.data.get(ATTR_FORECAST_DAILY)): return None forecast = daily_forecast.get("days") @@ -250,8 +249,7 @@ def _async_forecast_daily(self) -> list[Forecast] | None: @callback def _async_forecast_hourly(self) -> list[Forecast] | None: """Return the hourly forecast.""" - hourly_forecast = self.data.get(ATTR_FORECAST_HOURLY) - if not hourly_forecast: + if not (hourly_forecast := self.data.get(ATTR_FORECAST_HOURLY)): return None forecast = hourly_forecast.get("hours") diff --git a/homeassistant/components/wyoming/number.py b/homeassistant/components/wyoming/number.py index d9a58cc333329b..bd1bd50e3caf7e 100644 --- a/homeassistant/components/wyoming/number.py +++ b/homeassistant/components/wyoming/number.py @@ -57,8 +57,7 @@ async def async_added_to_hass(self) -> None: """When entity is added to Home Assistant.""" await super().async_added_to_hass() - state = await self.async_get_last_state() - if state is not None: + if (state := await self.async_get_last_state()) is not None: await self.async_set_native_value(float(state.state)) async def async_set_native_value(self, value: float) -> None: diff --git a/homeassistant/components/zha/helpers.py b/homeassistant/components/zha/helpers.py index 2440e18cf5389f..231bf24d35dcd7 100644 --- a/homeassistant/components/zha/helpers.py +++ b/homeassistant/components/zha/helpers.py @@ -1053,8 +1053,7 @@ def get_config_entry(hass: HomeAssistant) -> ConfigEntry: def async_get_zha_device_proxy(hass: HomeAssistant, device_id: str) -> ZHADeviceProxy: """Get a ZHA device for the given device registry id.""" device_registry = dr.async_get(hass) - registry_device = device_registry.async_get(device_id) - if not registry_device: + if not (registry_device := device_registry.async_get(device_id)): _LOGGER.error("Device id `%s` not found in registry", device_id) raise KeyError(f"Device id `{device_id}` not found in registry.") zha_gateway_proxy = get_zha_gateway_proxy(hass) diff --git a/homeassistant/components/zwave_js/event.py b/homeassistant/components/zwave_js/event.py index 8dae66c26ac595..a338f676bf7f84 100644 --- a/homeassistant/components/zwave_js/event.py +++ b/homeassistant/components/zwave_js/event.py @@ -46,8 +46,7 @@ def async_add_event(info: ZwaveDiscoveryInfo) -> None: def _cc_and_label(value: Value) -> str: """Return a string with the command class and label.""" - label = value.metadata.label - if label: + if label := value.metadata.label: label = label.lower() return f"{value.command_class_name.capitalize()} {label}".strip() diff --git a/homeassistant/helpers/check_config.py b/homeassistant/helpers/check_config.py index 4b5e2f277a020a..d497548ee29562 100644 --- a/homeassistant/helpers/check_config.py +++ b/homeassistant/helpers/check_config.py @@ -180,8 +180,7 @@ async def _get_integration( frontend_dependencies: set[str] = set() if "frontend" in components or "default_config" in components: - frontend = await _get_integration(hass, "frontend") - if frontend: + if frontend := await _get_integration(hass, "frontend"): await frontend.resolve_dependencies() frontend_dependencies = frontend.all_dependencies | {"frontend"} diff --git a/homeassistant/helpers/intent.py b/homeassistant/helpers/intent.py index 468539f5a9d011..af19519bb8e23a 100644 --- a/homeassistant/helpers/intent.py +++ b/homeassistant/helpers/intent.py @@ -1108,8 +1108,7 @@ async def async_call_service( if self.optional_slots: for key in self.optional_slots: - value = intent_obj.slots.get(key[0]) - if value: + if value := intent_obj.slots.get(key[0]): service_data[key[1]] = value["value"] await self._run_then_background( diff --git a/homeassistant/helpers/llm.py b/homeassistant/helpers/llm.py index 38d80d5649d00c..b39a0729cb0f44 100644 --- a/homeassistant/helpers/llm.py +++ b/homeassistant/helpers/llm.py @@ -331,9 +331,7 @@ def _async_get_api_prompt( floor: fr.FloorEntry | None = None if llm_context.device_id: device_reg = dr.async_get(self.hass) - device = device_reg.async_get(llm_context.device_id) - - if device: + if device := device_reg.async_get(llm_context.device_id): area_reg = ar.async_get(self.hass) if device.area_id and (area := area_reg.async_get_area(device.area_id)): floor_reg = fr.async_get(self.hass) @@ -654,8 +652,7 @@ def on_homeassistant_close(event: Event) -> None: fields = service_desc.get("fields", {}) for field, config in fields.items(): - field_description = config.get("description") - if not field_description: + if not (field_description := config.get("description")): field_description = config.get("name") key: vol.Marker if config.get("required"): diff --git a/homeassistant/helpers/network.py b/homeassistant/helpers/network.py index e39cc2de54735e..4ca5ad54166f96 100644 --- a/homeassistant/helpers/network.py +++ b/homeassistant/helpers/network.py @@ -218,8 +218,7 @@ def _get_request_host() -> str | None: raise NoURLAvailableError # partition the host to remove the port # because the raw host header can contain the port - host = request.headers.get(hdrs.HOST) - if host is None: + if (host := request.headers.get(hdrs.HOST)) is None: return None # IPv6 addresses are enclosed in brackets # use same logic as yarl and urllib to extract the host diff --git a/homeassistant/helpers/significant_change.py b/homeassistant/helpers/significant_change.py index 893ca7a3586bf2..f00e15a93ff0d9 100644 --- a/homeassistant/helpers/significant_change.py +++ b/homeassistant/helpers/significant_change.py @@ -223,9 +223,7 @@ def async_is_significant_change( self.last_approved_entities[new_state.entity_id] = (new_state, extra_arg) return True - functions = self.hass.data.get(DATA_FUNCTIONS) - - if functions is None: + if (functions := self.hass.data.get(DATA_FUNCTIONS)) is None: raise RuntimeError("Significant Change not initialized") check_significantly_changed = functions.get(new_state.domain) diff --git a/homeassistant/helpers/trace.py b/homeassistant/helpers/trace.py index 431a7a7d1f8cee..c94b7314491ca3 100644 --- a/homeassistant/helpers/trace.py +++ b/homeassistant/helpers/trace.py @@ -145,8 +145,7 @@ def trace_stack_push[_T]( def trace_stack_pop(trace_stack_var: ContextVar[list[Any] | None]) -> None: """Remove the top element from a trace stack.""" - trace_stack = trace_stack_var.get() - if trace_stack is not None: + if (trace_stack := trace_stack_var.get()) is not None: trace_stack.pop() diff --git a/tests/components/api/test_init.py b/tests/components/api/test_init.py index abce262fd12308..e64df0f2c1fa63 100644 --- a/tests/components/api/test_init.py +++ b/tests/components/api/test_init.py @@ -580,9 +580,7 @@ async def _stream_next_event(stream): data += dat last_new_line = dat == b"\n" - conv = data.decode("utf-8").strip()[6:] - - if conv != "ping": + if (conv := data.decode("utf-8").strip()[6:]) != "ping": break return json.loads(conv) diff --git a/tests/components/assist_pipeline/test_websocket.py b/tests/components/assist_pipeline/test_websocket.py index c1caf6f86a49f5..da3ae0a949c822 100644 --- a/tests/components/assist_pipeline/test_websocket.py +++ b/tests/components/assist_pipeline/test_websocket.py @@ -2641,13 +2641,11 @@ async def test_stt_cooldown_same_id( # Get response events error_data: dict[str, Any] | None = None msg = await client_1.receive_json() - event_type_1 = msg["event"]["type"] - if event_type_1 == "error": + if (event_type_1 := msg["event"]["type"]) == "error": error_data = msg["event"]["data"] msg = await client_2.receive_json() - event_type_2 = msg["event"]["type"] - if event_type_2 == "error": + if (event_type_2 := msg["event"]["type"]) == "error": error_data = msg["event"]["data"] # One should be a stt start, one should be an error diff --git a/tests/components/august/mocks.py b/tests/components/august/mocks.py index 43cc4957445be9..9c6dd2e8c81a1c 100644 --- a/tests/components/august/mocks.py +++ b/tests/components/august/mocks.py @@ -352,13 +352,11 @@ async def _mock_activities_from_fixture( hass: HomeAssistant, path: str ) -> list[Activity]: json_dict = await _load_json_fixture(hass, path) - activities = [] - for activity_json in json_dict: - activity = _activity_from_dict(activity_json) - if activity: - activities.append(activity) - - return activities + return [ + activity + for activity_json in json_dict + if (activity := _activity_from_dict(activity_json)) + ] async def _mock_lock_from_fixture(hass: HomeAssistant, path: str) -> LockDetail: diff --git a/tests/components/homekit_controller/common.py b/tests/components/homekit_controller/common.py index b94a267104b5ba..377d4e991b7f54 100644 --- a/tests/components/homekit_controller/common.py +++ b/tests/components/homekit_controller/common.py @@ -304,8 +304,7 @@ async def setup_test_component( domain = None for service in accessory.services: - service_name = service.type - if service_name in HOMEKIT_ACCESSORY_DISPATCH: + if (service_name := service.type) in HOMEKIT_ACCESSORY_DISPATCH: domain = HOMEKIT_ACCESSORY_DISPATCH[service_name] break diff --git a/tests/components/lutron_caseta/__init__.py b/tests/components/lutron_caseta/__init__.py index b27d30ac31f383..1807a9c090925c 100644 --- a/tests/components/lutron_caseta/__init__.py +++ b/tests/components/lutron_caseta/__init__.py @@ -284,10 +284,8 @@ def get_devices_by_domain(self, domain: str) -> list[dict]: :param domain: one of 'light', 'switch', 'cover', 'fan' or 'sensor' :returns list of zero or more of the devices """ - types = _LEAP_DEVICE_TYPES.get(domain) - # return immediately if not a supported domain - if types is None: + if (types := _LEAP_DEVICE_TYPES.get(domain)) is None: return [] return self.get_devices_by_types(types) diff --git a/tests/components/madvr/conftest.py b/tests/components/madvr/conftest.py index 3136e04b06bc44..58af882455f7be 100644 --- a/tests/components/madvr/conftest.py +++ b/tests/components/madvr/conftest.py @@ -76,9 +76,7 @@ def get_update_callback(mock_client: MagicMock): """ # Get all the calls made to set_update_callback - calls = mock_client.set_update_callback.call_args_list - - if not calls: + if not (calls := mock_client.set_update_callback.call_args_list): raise ValueError("set_update_callback was not called on the mock client") # Get the first (and usually only) call diff --git a/tests/components/recorder/db_schema_25.py b/tests/components/recorder/db_schema_25.py index d989cacb76a5e3..97a3e77e924578 100644 --- a/tests/components/recorder/db_schema_25.py +++ b/tests/components/recorder/db_schema_25.py @@ -35,7 +35,14 @@ MAX_LENGTH_STATE_ENTITY_ID, MAX_LENGTH_STATE_STATE, ) -from homeassistant.core import Context, Event, EventOrigin, State, split_entity_id +from homeassistant.core import ( + Context, + Event, + EventOrigin, + EventStateChangedData, + State, + split_entity_id, +) from homeassistant.helpers.typing import UNDEFINED, UndefinedType import homeassistant.util.dt as dt_util @@ -259,12 +266,12 @@ def from_event(event: Event) -> StateAttributes: @staticmethod def shared_attrs_from_event( - event: Event, exclude_attrs_by_domain: dict[str, set[str]] + event: Event[EventStateChangedData], + exclude_attrs_by_domain: dict[str, set[str]], ) -> str: """Create shared_attrs from a state_changed event.""" - state: State | None = event.data.get("new_state") # None state means the state was removed from the state machine - if state is None: + if (state := event.data.get("new_state")) is None: return "{}" domain = split_entity_id(state.entity_id)[0] exclude_attrs = ( diff --git a/tests/components/recorder/db_schema_28.py b/tests/components/recorder/db_schema_28.py index 8c984b61f6c01e..273eec739370c0 100644 --- a/tests/components/recorder/db_schema_28.py +++ b/tests/components/recorder/db_schema_28.py @@ -42,7 +42,14 @@ MAX_LENGTH_STATE_ENTITY_ID, MAX_LENGTH_STATE_STATE, ) -from homeassistant.core import Context, Event, EventOrigin, State, split_entity_id +from homeassistant.core import ( + Context, + Event, + EventOrigin, + EventStateChangedData, + State, + split_entity_id, +) import homeassistant.util.dt as dt_util # SQLAlchemy Schema @@ -403,12 +410,12 @@ def from_event(event: Event) -> StateAttributes: @staticmethod def shared_attrs_from_event( - event: Event, exclude_attrs_by_domain: dict[str, set[str]] + event: Event[EventStateChangedData], + exclude_attrs_by_domain: dict[str, set[str]], ) -> str: """Create shared_attrs from a state_changed event.""" - state: State | None = event.data.get("new_state") # None state means the state was removed from the state machine - if state is None: + if (state := event.data.get("new_state")) is None: return "{}" domain = split_entity_id(state.entity_id)[0] exclude_attrs = ( diff --git a/tests/components/recorder/db_schema_30.py b/tests/components/recorder/db_schema_30.py index 97c33334111e24..0c70e0c2e99cfc 100644 --- a/tests/components/recorder/db_schema_30.py +++ b/tests/components/recorder/db_schema_30.py @@ -47,7 +47,14 @@ MAX_LENGTH_STATE_ENTITY_ID, MAX_LENGTH_STATE_STATE, ) -from homeassistant.core import Context, Event, EventOrigin, State, split_entity_id +from homeassistant.core import ( + Context, + Event, + EventOrigin, + EventStateChangedData, + State, + split_entity_id, +) from homeassistant.helpers import entity_registry as er from homeassistant.helpers.json import JSON_DUMP, json_bytes import homeassistant.util.dt as dt_util @@ -507,15 +514,14 @@ def from_event(event: Event) -> StateAttributes: @staticmethod def shared_attrs_bytes_from_event( - event: Event, + event: Event[EventStateChangedData], entity_registry: er.EntityRegistry, exclude_attrs_by_domain: dict[str, set[str]], dialect: SupportedDialect | None, ) -> bytes: """Create shared_attrs from a state_changed event.""" - state: State | None = event.data.get("new_state") # None state means the state was removed from the state machine - if state is None: + if (state := event.data.get("new_state")) is None: return b"{}" domain = split_entity_id(state.entity_id)[0] exclude_attrs = ( diff --git a/tests/components/recorder/db_schema_32.py b/tests/components/recorder/db_schema_32.py index 39ddb8e314838e..66662546088c07 100644 --- a/tests/components/recorder/db_schema_32.py +++ b/tests/components/recorder/db_schema_32.py @@ -48,7 +48,14 @@ MAX_LENGTH_STATE_ENTITY_ID, MAX_LENGTH_STATE_STATE, ) -from homeassistant.core import Context, Event, EventOrigin, State, split_entity_id +from homeassistant.core import ( + Context, + Event, + EventOrigin, + EventStateChangedData, + State, + split_entity_id, +) from homeassistant.helpers import entity_registry as er from homeassistant.helpers.json import JSON_DUMP, json_bytes import homeassistant.util.dt as dt_util @@ -506,15 +513,14 @@ def from_event(event: Event) -> StateAttributes: @staticmethod def shared_attrs_bytes_from_event( - event: Event, + event: Event[EventStateChangedData], entity_registry: er.EntityRegistry, exclude_attrs_by_domain: dict[str, set[str]], dialect: SupportedDialect | None, ) -> bytes: """Create shared_attrs from a state_changed event.""" - state: State | None = event.data.get("new_state") # None state means the state was removed from the state machine - if state is None: + if (state := event.data.get("new_state")) is None: return b"{}" domain = split_entity_id(state.entity_id)[0] exclude_attrs = ( diff --git a/tests/components/recorder/db_schema_42.py b/tests/components/recorder/db_schema_42.py index efeade46562995..253dd2670e5ac3 100644 --- a/tests/components/recorder/db_schema_42.py +++ b/tests/components/recorder/db_schema_42.py @@ -64,7 +64,7 @@ MAX_LENGTH_STATE_ENTITY_ID, MAX_LENGTH_STATE_STATE, ) -from homeassistant.core import Context, Event, EventOrigin, State +from homeassistant.core import Context, Event, EventOrigin, EventStateChangedData, State from homeassistant.helpers.json import JSON_DUMP, json_bytes, json_bytes_strip_null import homeassistant.util.dt as dt_util from homeassistant.util.json import ( @@ -385,8 +385,7 @@ def hash_shared_data_bytes(shared_data_bytes: bytes) -> int: def to_native(self) -> dict[str, Any]: """Convert to an event data dictionary.""" - shared_data = self.shared_data - if shared_data is None: + if (shared_data := self.shared_data) is None: return {} try: return cast(dict[str, Any], json_loads(shared_data)) @@ -573,13 +572,12 @@ def __repr__(self) -> str: @staticmethod def shared_attrs_bytes_from_event( - event: Event, + event: Event[EventStateChangedData], dialect: SupportedDialect | None, ) -> bytes: """Create shared_attrs from a state_changed event.""" - state: State | None = event.data.get("new_state") # None state means the state was removed from the state machine - if state is None: + if (state := event.data.get("new_state")) is None: return b"{}" if state_info := state.state_info: unrecorded_attributes = state_info["unrecorded_attributes"] @@ -627,8 +625,7 @@ def hash_shared_attrs_bytes(shared_attrs_bytes: bytes) -> int: def to_native(self) -> dict[str, Any]: """Convert to a state attributes dictionary.""" - shared_attrs = self.shared_attrs - if shared_attrs is None: + if (shared_attrs := self.shared_attrs) is None: return {} try: return cast(dict[str, Any], json_loads(shared_attrs)) diff --git a/tests/components/recorder/db_schema_43.py b/tests/components/recorder/db_schema_43.py index 8e77e8782ee345..b84b26f0374a84 100644 --- a/tests/components/recorder/db_schema_43.py +++ b/tests/components/recorder/db_schema_43.py @@ -394,8 +394,7 @@ def hash_shared_data_bytes(shared_data_bytes: bytes) -> int: def to_native(self) -> dict[str, Any]: """Convert to an event data dictionary.""" - shared_data = self.shared_data - if shared_data is None: + if (shared_data := self.shared_data) is None: return {} try: return cast(dict[str, Any], json_loads(shared_data)) @@ -498,9 +497,8 @@ def _last_updated_isotime(self) -> str | None: @staticmethod def from_event(event: Event[EventStateChangedData]) -> States: """Create object from a state_changed event.""" - state = event.data["new_state"] # None state means the state was removed from the state machine - if state is None: + if (state := event.data["new_state"]) is None: state_value = "" last_updated_ts = event.time_fired_timestamp last_changed_ts = None @@ -637,8 +635,7 @@ def hash_shared_attrs_bytes(shared_attrs_bytes: bytes) -> int: def to_native(self) -> dict[str, Any]: """Convert to a state attributes dictionary.""" - shared_attrs = self.shared_attrs - if shared_attrs is None: + if (shared_attrs := self.shared_attrs) is None: return {} try: return cast(dict[str, Any], json_loads(shared_attrs)) diff --git a/tests/components/refoss/__init__.py b/tests/components/refoss/__init__.py index 1a3e02dac62cd0..519f4b6920a4e5 100644 --- a/tests/components/refoss/__init__.py +++ b/tests/components/refoss/__init__.py @@ -42,8 +42,7 @@ async def broadcast_msg(self, wait_for: int = 0): updated_infos = [] for info in mock_infos.values(): - uuid = info.uuid - if uuid not in last_mock_infos: + if (uuid := info.uuid) not in last_mock_infos: new_infos.append(info) else: last_info = self.last_mock_infos[uuid] diff --git a/tests/components/stream/test_ll_hls.py b/tests/components/stream/test_ll_hls.py index 5577076830b560..df8a33ad56815f 100644 --- a/tests/components/stream/test_ll_hls.py +++ b/tests/components/stream/test_ll_hls.py @@ -174,8 +174,7 @@ async def test_ll_hls_stream( playlist = await playlist_response.text() segment_re = re.compile(r"^(?P./segment/\d+\.m4s)") for line in playlist.splitlines(): - match = segment_re.match(line) - if match: + if match := segment_re.match(line): segment_url = "/" + match.group("segment_url") segment_response = await hls_client.get(segment_url) assert segment_response.status == HTTPStatus.OK @@ -209,8 +208,7 @@ def check_part_is_moof_mdat(data: bytes): segment_duration = 0 datetimes = deque() for line in playlist.splitlines(): - match = part_re.match(line) - if match: + if match := part_re.match(line): # Fetch all completed part segments part_durations.append(float(match.group("part_duration"))) part_segment_url = "/" + match.group("part_url") @@ -221,8 +219,7 @@ def check_part_is_moof_mdat(data: bytes): assert check_part_is_moof_mdat(await part_segment_response.read()) tested[part_re] = True continue - match = datetime_re.match(line) - if match: + if match := datetime_re.match(line): datetimes.append(parser.parse(match.group("datetime"))) # Check that segment durations are consistent with PROGRAM-DATE-TIME if len(datetimes) > 1: @@ -235,8 +232,7 @@ def check_part_is_moof_mdat(data: bytes): ) tested[datetime_re] = True continue - match = inf_re.match(line) - if match: + if match := inf_re.match(line): segment_duration = float(match.group("segment_duration")) # Check that segment durations are consistent with part durations if len(part_durations) > 1: diff --git a/tests/components/zha/common.py b/tests/components/zha/common.py index 1dd1e5f81aa1e8..26afb79c907635 100644 --- a/tests/components/zha/common.py +++ b/tests/components/zha/common.py @@ -132,8 +132,7 @@ def find_entity_id( This is used to get the entity id in order to get the state from the state machine so that we can test state changes. """ - entities = find_entity_ids(domain, zha_device, hass) - if not entities: + if not (entities := find_entity_ids(domain, zha_device, hass)): return None if qualifier: for entity_id in entities: diff --git a/tests/conftest.py b/tests/conftest.py index c46ed0407e54a9..1fc2add3a3a29a 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -235,9 +235,7 @@ def check_real[**_P, _R](func: Callable[_P, Coroutine[Any, Any, _R]]): @functools.wraps(func) async def guard_func(*args: _P.args, **kwargs: _P.kwargs) -> _R: - real = kwargs.pop("_test_real", None) - - if not real: + if not kwargs.pop("_test_real", None): raise RuntimeError( f'Forgot to mock or pass "_test_real=True" to {func.__name__}' ) diff --git a/tests/helpers/test_schema_config_entry_flow.py b/tests/helpers/test_schema_config_entry_flow.py index e67525253bcf78..b365bc74321bb7 100644 --- a/tests/helpers/test_schema_config_entry_flow.py +++ b/tests/helpers/test_schema_config_entry_flow.py @@ -51,9 +51,7 @@ class FlowManager(data_entry_flow.FlowManager): async def async_create_flow(self, handler_key, *, context, data): """Test create flow.""" - handler = handlers.get(handler_key) - - if handler is None: + if (handler := handlers.get(handler_key)) is None: raise data_entry_flow.UnknownHandler flow = handler() diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index 628aea20900ba2..aeed0ba9963e38 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -1220,8 +1220,7 @@ async def test_timestamp_local(hass: HomeAssistant) -> None: ) def test_as_datetime(hass: HomeAssistant, input) -> None: """Test converting a timestamp string to a date object.""" - expected = dt_util.parse_datetime(input) - if expected is not None: + if (expected := dt_util.parse_datetime(input)) is not None: expected = str(expected) assert ( template.Template(f"{{{{ as_datetime('{input}') }}}}", hass).async_render() diff --git a/tests/test_config_entries.py b/tests/test_config_entries.py index aba85a35349d32..6c115cf1408344 100644 --- a/tests/test_config_entries.py +++ b/tests/test_config_entries.py @@ -135,8 +135,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Mock setup entry.""" - slow = entry.data["slow"] - if slow: + if entry.data["slow"]: await slow_config_entry_setup_future return True nonlocal attempts diff --git a/tests/test_data_entry_flow.py b/tests/test_data_entry_flow.py index 74a55cb4989d75..f254b33f55a75f 100644 --- a/tests/test_data_entry_flow.py +++ b/tests/test_data_entry_flow.py @@ -28,9 +28,7 @@ def __init__(self) -> None: async def async_create_flow(self, handler_key, *, context, data): """Test create flow.""" - handler = self._handlers.get(handler_key) - - if handler is None: + if (handler := self._handlers.get(handler_key)) is None: raise data_entry_flow.UnknownHandler flow = handler()