From 84618fa831e1ea80ab376613b43879c950c62c89 Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Sat, 30 Oct 2021 16:33:42 +0200 Subject: [PATCH] Use assignment expressions 30 (#58714) --- homeassistant/components/aruba/device_tracker.py | 3 +-- homeassistant/components/automation/__init__.py | 12 +++--------- homeassistant/components/bond/light.py | 3 +-- homeassistant/components/camera/__init__.py | 8 ++------ homeassistant/components/dlna_dmr/config_flow.py | 3 +-- homeassistant/components/dlna_dmr/media_player.py | 9 +++------ homeassistant/components/hangouts/hangouts_bot.py | 4 +--- .../components/homekit_controller/config_flow.py | 3 +-- homeassistant/components/lcn/helpers.py | 4 +--- homeassistant/components/logbook/__init__.py | 7 ++----- homeassistant/components/media_player/__init__.py | 6 ++---- homeassistant/components/media_source/models.py | 4 +--- homeassistant/components/melcloud/__init__.py | 3 +-- homeassistant/components/octoprint/binary_sensor.py | 3 +-- homeassistant/components/octoprint/sensor.py | 3 +-- homeassistant/components/pandora/media_player.py | 9 +++------ homeassistant/components/recorder/statistics.py | 3 +-- homeassistant/components/rflink/light.py | 3 +-- homeassistant/components/system_log/__init__.py | 3 +-- homeassistant/components/tado/climate.py | 3 +-- homeassistant/components/thomson/device_tracker.py | 3 +-- homeassistant/components/todoist/calendar.py | 3 +-- .../components/yamaha_musiccast/media_player.py | 4 +--- homeassistant/components/zeroconf/__init__.py | 4 +--- 24 files changed, 33 insertions(+), 77 deletions(-) diff --git a/homeassistant/components/aruba/device_tracker.py b/homeassistant/components/aruba/device_tracker.py index 49074dba3be..e9799411197 100644 --- a/homeassistant/components/aruba/device_tracker.py +++ b/homeassistant/components/aruba/device_tracker.py @@ -125,8 +125,7 @@ class ArubaDeviceScanner(DeviceScanner): devices = {} for device in devices_result: - match = _DEVICES_REGEX.search(device.decode("utf-8")) - if match: + if match := _DEVICES_REGEX.search(device.decode("utf-8")): devices[match.group("ip")] = { "ip": match.group("ip"), "mac": match.group("mac").upper(), diff --git a/homeassistant/components/automation/__init__.py b/homeassistant/components/automation/__init__.py index 08764b35ea3..699fdc8745b 100644 --- a/homeassistant/components/automation/__init__.py +++ b/homeassistant/components/automation/__init__.py @@ -156,9 +156,7 @@ def entities_in_automation(hass: HomeAssistant, entity_id: str) -> list[str]: component = hass.data[DOMAIN] - automation_entity = component.get_entity(entity_id) - - if automation_entity is None: + if (automation_entity := component.get_entity(entity_id)) is None: return [] return list(automation_entity.referenced_entities) @@ -187,9 +185,7 @@ def devices_in_automation(hass: HomeAssistant, entity_id: str) -> list[str]: component = hass.data[DOMAIN] - automation_entity = component.get_entity(entity_id) - - if automation_entity is None: + if (automation_entity := component.get_entity(entity_id)) is None: return [] return list(automation_entity.referenced_devices) @@ -218,9 +214,7 @@ def areas_in_automation(hass: HomeAssistant, entity_id: str) -> list[str]: component = hass.data[DOMAIN] - automation_entity = component.get_entity(entity_id) - - if automation_entity is None: + if (automation_entity := component.get_entity(entity_id)) is None: return [] return list(automation_entity.referenced_areas) diff --git a/homeassistant/components/bond/light.py b/homeassistant/components/bond/light.py index dd4699ad006..255f848c167 100644 --- a/homeassistant/components/bond/light.py +++ b/homeassistant/components/bond/light.py @@ -180,8 +180,7 @@ class BondLight(BondBaseLight, BondEntity, LightEntity): async def async_turn_on(self, **kwargs: Any) -> None: """Turn on the light.""" - brightness = kwargs.get(ATTR_BRIGHTNESS) - if brightness: + if brightness := kwargs.get(ATTR_BRIGHTNESS): await self._hub.bond.action( self._device.device_id, Action.set_brightness(round((brightness * 100) / 255)), diff --git a/homeassistant/components/camera/__init__.py b/homeassistant/components/camera/__init__.py index 5a3d730e7d3..4aa443c2ed6 100644 --- a/homeassistant/components/camera/__init__.py +++ b/homeassistant/components/camera/__init__.py @@ -275,9 +275,7 @@ def _get_camera_from_entity_id(hass: HomeAssistant, entity_id: str) -> Camera: if (component := hass.data.get(DOMAIN)) is None: raise HomeAssistantError("Camera integration not set up") - camera = component.get_entity(entity_id) - - if camera is None: + if (camera := component.get_entity(entity_id)) is None: raise HomeAssistantError("Camera not found") if not camera.is_on: @@ -596,9 +594,7 @@ class CameraView(HomeAssistantView): async def get(self, request: web.Request, entity_id: str) -> web.StreamResponse: """Start a GET request.""" - camera = self.component.get_entity(entity_id) - - if camera is None: + if (camera := self.component.get_entity(entity_id)) is None: raise web.HTTPNotFound() camera = cast(Camera, camera) diff --git a/homeassistant/components/dlna_dmr/config_flow.py b/homeassistant/components/dlna_dmr/config_flow.py index 454a28c9f7d..2ac74fb4cbd 100644 --- a/homeassistant/components/dlna_dmr/config_flow.py +++ b/homeassistant/components/dlna_dmr/config_flow.py @@ -81,8 +81,7 @@ class DlnaDmrFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): LOGGER.debug("async_step_user: user_input: %s", user_input) if user_input is not None: - host = user_input.get(CONF_HOST) - if not host: + if not (host := user_input.get(CONF_HOST)): # No device chosen, user might want to directly enter an URL return await self.async_step_manual() # User has chosen a device, ask for confirmation diff --git a/homeassistant/components/dlna_dmr/media_player.py b/homeassistant/components/dlna_dmr/media_player.py index 2b699735108..68a41e1fa62 100644 --- a/homeassistant/components/dlna_dmr/media_player.py +++ b/homeassistant/components/dlna_dmr/media_player.py @@ -613,8 +613,7 @@ class DlnaDmrEntity(MediaPlayerEntity): metadata: dict[str, Any] = extra.get("metadata") or {} title = extra.get("title") or metadata.get("title") or "Home Assistant" - thumb = extra.get("thumb") - if thumb: + if thumb := extra.get("thumb"): metadata["album_art_uri"] = thumb # Translate metadata keys from HA names to DIDL-Lite names @@ -666,8 +665,7 @@ class DlnaDmrEntity(MediaPlayerEntity): if not self._device: return None - play_mode = self._device.play_mode - if not play_mode: + if not (play_mode := self._device.play_mode): return None if play_mode == PlayMode.VENDOR_DEFINED: @@ -700,8 +698,7 @@ class DlnaDmrEntity(MediaPlayerEntity): if not self._device: return None - play_mode = self._device.play_mode - if not play_mode: + if not (play_mode := self._device.play_mode): return None if play_mode == PlayMode.VENDOR_DEFINED: diff --git a/homeassistant/components/hangouts/hangouts_bot.py b/homeassistant/components/hangouts/hangouts_bot.py index 16872079be3..5c0625411ae 100644 --- a/homeassistant/components/hangouts/hangouts_bot.py +++ b/homeassistant/components/hangouts/hangouts_bot.py @@ -182,9 +182,7 @@ class HangoutsBot: """Detect a matching intent.""" for intent_type, data in intents.items(): for matcher in data.get(CONF_MATCHERS, []): - match = matcher.match(text) - - if not match: + if not (match := matcher.match(text)): continue if intent_type == INTENT_HELP: return await self.hass.helpers.intent.async_handle( diff --git a/homeassistant/components/homekit_controller/config_flow.py b/homeassistant/components/homekit_controller/config_flow.py index cc4addfae4f..02b4c396783 100644 --- a/homeassistant/components/homekit_controller/config_flow.py +++ b/homeassistant/components/homekit_controller/config_flow.py @@ -75,8 +75,7 @@ def ensure_pin_format(pin, allow_insecure_setup_codes=None): If incorrect code is entered, an exception is raised. """ - match = PIN_FORMAT.search(pin.strip()) - if not match: + if not (match := PIN_FORMAT.search(pin.strip())): raise aiohomekit.exceptions.MalformedPinError(f"Invalid PIN code f{pin}") pin_without_dashes = "".join(match.groups()) if not allow_insecure_setup_codes and pin_without_dashes in INSECURE_CODES: diff --git a/homeassistant/components/lcn/helpers.py b/homeassistant/components/lcn/helpers.py index feb27e337e8..b879c2d3f72 100644 --- a/homeassistant/components/lcn/helpers.py +++ b/homeassistant/components/lcn/helpers.py @@ -304,10 +304,8 @@ async def async_update_device_config( device_connection: DeviceConnectionType, device_config: ConfigType ) -> None: """Fill missing values in device_config with infos from LCN bus.""" - is_group = device_config[CONF_ADDRESS][2] - # fetch serial info if device is module - if not is_group: # is module + if not (is_group := device_config[CONF_ADDRESS][2]): # is module await device_connection.serial_known if device_config[CONF_HARDWARE_SERIAL] == -1: device_config[CONF_HARDWARE_SERIAL] = device_connection.hardware_serial diff --git a/homeassistant/components/logbook/__init__.py b/homeassistant/components/logbook/__init__.py index a758f850b93..89e70f346ed 100644 --- a/homeassistant/components/logbook/__init__.py +++ b/homeassistant/components/logbook/__init__.py @@ -193,9 +193,7 @@ class LogbookView(HomeAssistantView): async def get(self, request, datetime=None): """Retrieve logbook entries.""" if datetime: - datetime = dt_util.parse_datetime(datetime) - - if datetime is None: + if (datetime := dt_util.parse_datetime(datetime)) is None: return self.json_message("Invalid datetime", HTTPStatus.BAD_REQUEST) else: datetime = dt_util.start_of_local_day() @@ -219,8 +217,7 @@ class LogbookView(HomeAssistantView): end_day = start_day + timedelta(days=period) else: start_day = datetime - end_day = dt_util.parse_datetime(end_time) - if end_day is None: + if (end_day := dt_util.parse_datetime(end_time)) is None: return self.json_message("Invalid end_time", HTTPStatus.BAD_REQUEST) hass = request.app["hass"] diff --git a/homeassistant/components/media_player/__init__.py b/homeassistant/components/media_player/__init__.py index 5f15270563a..41ebd93f3b5 100644 --- a/homeassistant/components/media_player/__init__.py +++ b/homeassistant/components/media_player/__init__.py @@ -1026,8 +1026,7 @@ class MediaPlayerImageView(HomeAssistantView): media_content_id: str | None = None, ) -> web.Response: """Start a get request.""" - player = self.component.get_entity(entity_id) - if player is None: + if (player := self.component.get_entity(entity_id)) is None: status = ( HTTPStatus.NOT_FOUND if request[KEY_AUTHENTICATED] @@ -1071,9 +1070,8 @@ async def websocket_handle_thumbnail(hass, connection, msg): Async friendly. """ component = hass.data[DOMAIN] - player = component.get_entity(msg["entity_id"]) - if player is None: + if (player := component.get_entity(msg["entity_id"])) is None: connection.send_message( websocket_api.error_message(msg["id"], ERR_NOT_FOUND, "Entity not found") ) diff --git a/homeassistant/components/media_source/models.py b/homeassistant/components/media_source/models.py index 32f0070176f..b48ee784c23 100644 --- a/homeassistant/components/media_source/models.py +++ b/homeassistant/components/media_source/models.py @@ -93,9 +93,7 @@ class MediaSourceItem: @classmethod def from_uri(cls, hass: HomeAssistant, uri: str) -> MediaSourceItem: """Create an item from a uri.""" - match = URI_SCHEME_REGEX.match(uri) - - if not match: + if not (match := URI_SCHEME_REGEX.match(uri)): raise ValueError("Invalid media source URI") domain = match.group("domain") diff --git a/homeassistant/components/melcloud/__init__.py b/homeassistant/components/melcloud/__init__.py index 3ab3f603dbd..518d902a7e1 100644 --- a/homeassistant/components/melcloud/__init__.py +++ b/homeassistant/components/melcloud/__init__.py @@ -130,8 +130,7 @@ class MelCloudDevice: def device_info(self) -> DeviceInfo: """Return a device description for device registry.""" model = None - unit_infos = self.device.units - if unit_infos is not None: + if (unit_infos := self.device.units) is not None: model = ", ".join([x["model"] for x in unit_infos if x["model"]]) return DeviceInfo( connections={(CONNECTION_NETWORK_MAC, self.device.mac)}, diff --git a/homeassistant/components/octoprint/binary_sensor.py b/homeassistant/components/octoprint/binary_sensor.py index 1adb04d3417..221fc453e07 100644 --- a/homeassistant/components/octoprint/binary_sensor.py +++ b/homeassistant/components/octoprint/binary_sensor.py @@ -68,8 +68,7 @@ class OctoPrintBinarySensorBase(CoordinatorEntity, BinarySensorEntity): @property def is_on(self): """Return true if binary sensor is on.""" - printer = self.coordinator.data["printer"] - if not printer: + if not (printer := self.coordinator.data["printer"]): return None return bool(self._get_flag_state(printer)) diff --git a/homeassistant/components/octoprint/sensor.py b/homeassistant/components/octoprint/sensor.py index 5a9614c69b4..8682f246aa3 100644 --- a/homeassistant/components/octoprint/sensor.py +++ b/homeassistant/components/octoprint/sensor.py @@ -130,8 +130,7 @@ class OctoPrintJobPercentageSensor(OctoPrintSensorBase): if not job: return None - state = job.progress.completion - if not state: + if not (state := job.progress.completion): return 0 return round(state, 2) diff --git a/homeassistant/components/pandora/media_player.py b/homeassistant/components/pandora/media_player.py index 33ea72f94ff..902ccebb191 100644 --- a/homeassistant/components/pandora/media_player.py +++ b/homeassistant/components/pandora/media_player.py @@ -274,8 +274,7 @@ class PandoraMediaPlayer(MediaPlayerEntity): def _update_current_station(self, response): """Update current station.""" - station_match = re.search(STATION_PATTERN, response) - if station_match: + if station_match := re.search(STATION_PATTERN, response): self._station = station_match.group(1) _LOGGER.debug("Got station as: %s", self._station) else: @@ -283,8 +282,7 @@ class PandoraMediaPlayer(MediaPlayerEntity): def _update_current_song(self, response): """Update info about current song.""" - song_match = re.search(CURRENT_SONG_PATTERN, response) - if song_match: + if song_match := re.search(CURRENT_SONG_PATTERN, response): ( self._media_title, self._media_artist, @@ -343,8 +341,7 @@ class PandoraMediaPlayer(MediaPlayerEntity): _LOGGER.debug("Getting stations: %s", station_lines) self._stations = [] for line in station_lines.split("\r\n"): - match = re.search(r"\d+\).....(.+)", line) - if match: + if match := re.search(r"\d+\).....(.+)", line): station = match.group(1).strip() _LOGGER.debug("Found station %s", station) self._stations.append(station) diff --git a/homeassistant/components/recorder/statistics.py b/homeassistant/components/recorder/statistics.py index edac688bdd1..e5fe84cc874 100644 --- a/homeassistant/components/recorder/statistics.py +++ b/homeassistant/components/recorder/statistics.py @@ -620,8 +620,7 @@ def list_statistic_ids( platform_statistic_ids = platform.list_statistic_ids(hass, statistic_type) for statistic_id, info in platform_statistic_ids.items(): - unit = info["unit_of_measurement"] - if unit is not None: + if (unit := info["unit_of_measurement"]) is not None: # Display unit according to user settings unit = _configured_unit(unit, units) platform_statistic_ids[statistic_id]["unit_of_measurement"] = unit diff --git a/homeassistant/components/rflink/light.py b/homeassistant/components/rflink/light.py index 5a0d6766179..a4017275dea 100644 --- a/homeassistant/components/rflink/light.py +++ b/homeassistant/components/rflink/light.py @@ -254,8 +254,7 @@ class ToggleRflinkLight(SwitchableRflinkDevice, LightEntity): """Adjust state if Rflink picks up a remote command for this device.""" self.cancel_queued_send_commands() - command = event["command"] - if command == "on": + if event["command"] == "on": # if the state is unknown or false, it gets set as true # if the state is true, it gets set as false self._state = self._state in [None, False] diff --git a/homeassistant/components/system_log/__init__.py b/homeassistant/components/system_log/__init__.py index 8a88eef7bfc..fa8df5af870 100644 --- a/homeassistant/components/system_log/__init__.py +++ b/homeassistant/components/system_log/__init__.py @@ -81,8 +81,7 @@ def _figure_out_source(record, call_stack, hass): for pathname in reversed(stack): # Try to match with a file within Home Assistant - match = re.match(paths_re, pathname[0]) - if match: + if match := re.match(paths_re, pathname[0]): return [match.group(1), pathname[1]] # Ok, we don't know what this is return (record.pathname, record.lineno) diff --git a/homeassistant/components/tado/climate.py b/homeassistant/components/tado/climate.py index aa9852f643f..5c0c4debf80 100644 --- a/homeassistant/components/tado/climate.py +++ b/homeassistant/components/tado/climate.py @@ -398,8 +398,7 @@ class TadoClimate(TadoZoneEntity, ClimateEntity): def set_temperature(self, **kwargs): """Set new target temperature.""" - temperature = kwargs.get(ATTR_TEMPERATURE) - if temperature is None: + if (temperature := kwargs.get(ATTR_TEMPERATURE)) is None: return if self._current_tado_hvac_mode not in ( diff --git a/homeassistant/components/thomson/device_tracker.py b/homeassistant/components/thomson/device_tracker.py index 4922117b64c..98302ad396a 100644 --- a/homeassistant/components/thomson/device_tracker.py +++ b/homeassistant/components/thomson/device_tracker.py @@ -110,8 +110,7 @@ class ThomsonDeviceScanner(DeviceScanner): devices = {} for device in devices_result: - match = _DEVICES_REGEX.search(device.decode("utf-8")) - if match: + if match := _DEVICES_REGEX.search(device.decode("utf-8")): devices[match.group("ip")] = { "ip": match.group("ip"), "mac": match.group("mac").upper(), diff --git a/homeassistant/components/todoist/calendar.py b/homeassistant/components/todoist/calendar.py index 51f4e859a1f..7097446ba4f 100644 --- a/homeassistant/components/todoist/calendar.py +++ b/homeassistant/components/todoist/calendar.py @@ -233,8 +233,7 @@ def _parse_due_date(data: dict, gmt_string) -> datetime | None: # Add time information to date only strings. if len(data["date"]) == 10: return datetime.fromisoformat(data["date"]).replace(tzinfo=dt.UTC) - nowtime = dt.parse_datetime(data["date"]) - if not nowtime: + if not (nowtime := dt.parse_datetime(data["date"])): return None if nowtime.tzinfo is None: data["date"] += gmt_string diff --git a/homeassistant/components/yamaha_musiccast/media_player.py b/homeassistant/components/yamaha_musiccast/media_player.py index 502a0b0c3f1..b1d0bdcd2e9 100644 --- a/homeassistant/components/yamaha_musiccast/media_player.py +++ b/homeassistant/components/yamaha_musiccast/media_player.py @@ -342,9 +342,7 @@ class MusicCastMediaPlayer(MusicCastDeviceEntity, MediaPlayerEntity): parts = media_id.split(":") if parts[0] == "list": - index = parts[3] - - if index == "-1": + if (index := parts[3]) == "-1": index = "0" await self.coordinator.musiccast.play_list_media(index, self._zone_id) diff --git a/homeassistant/components/zeroconf/__init__.py b/homeassistant/components/zeroconf/__init__.py index 8b845f303cd..4062200972d 100644 --- a/homeassistant/components/zeroconf/__init__.py +++ b/homeassistant/components/zeroconf/__init__.py @@ -469,9 +469,7 @@ def info_from_service(service: AsyncServiceInfo) -> HaServiceInfo | None: if isinstance(value, bytes): properties[key] = value.decode("utf-8") - addresses = service.addresses - - if not addresses: + if not (addresses := service.addresses): return None if (host := _first_non_link_local_or_v6_address(addresses)) is None: return None