From ae302bbec09d3d7f53d86afd0c9fe5009c4f9c19 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Fri, 13 Jan 2023 13:19:38 +0200 Subject: [PATCH] Make use of str.removeprefix and .removesuffix (#85584) --- homeassistant/components/airzone/__init__.py | 2 +- homeassistant/components/apcupsd/sensor.py | 2 +- homeassistant/components/apple_tv/__init__.py | 7 +------ homeassistant/components/august/entity.py | 4 +--- homeassistant/components/bosch_shc/config_flow.py | 2 +- homeassistant/components/denon/media_player.py | 12 ++++++------ homeassistant/components/doorbird/config_flow.py | 4 +--- homeassistant/components/esphome/config_flow.py | 2 +- homeassistant/components/flux_led/__init__.py | 2 +- homeassistant/components/frontend/__init__.py | 2 +- homeassistant/components/google_assistant/logbook.py | 4 +--- homeassistant/components/huawei_lte/__init__.py | 5 ++--- .../hunterdouglas_powerview/config_flow.py | 8 ++------ homeassistant/components/hyperion/camera.py | 2 +- homeassistant/components/isy994/config_flow.py | 6 ++---- homeassistant/components/kodi/config_flow.py | 2 +- homeassistant/components/lookin/config_flow.py | 2 +- homeassistant/components/plex/services.py | 2 +- homeassistant/components/recorder/util.py | 2 +- homeassistant/components/sonos/helpers.py | 4 ++-- homeassistant/components/spotify/browse_media.py | 2 +- homeassistant/components/spotify/media_player.py | 3 +-- homeassistant/components/spotify/util.py | 2 +- homeassistant/components/zha/config_flow.py | 2 +- 24 files changed, 33 insertions(+), 52 deletions(-) diff --git a/homeassistant/components/airzone/__init__.py b/homeassistant/components/airzone/__init__.py index 1622bdb7bf3..de75bf03d45 100644 --- a/homeassistant/components/airzone/__init__.py +++ b/homeassistant/components/airzone/__init__.py @@ -45,7 +45,7 @@ async def _async_migrate_unique_ids( entity_unique_id = entity_entry.unique_id if entity_unique_id.startswith(entry_id): - new_unique_id = f"{unique_id}{entity_unique_id[len(entry_id):]}" + new_unique_id = f"{unique_id}{entity_unique_id.removeprefix(entry_id)}" _LOGGER.debug( "Migrating unique_id from [%s] to [%s]", entity_unique_id, diff --git a/homeassistant/components/apcupsd/sensor.py b/homeassistant/components/apcupsd/sensor.py index 845e482d12c..27d315f90fd 100644 --- a/homeassistant/components/apcupsd/sensor.py +++ b/homeassistant/components/apcupsd/sensor.py @@ -474,7 +474,7 @@ def infer_unit(value: str) -> tuple[str, str | None]: for unit in ALL_UNITS: if value.endswith(unit): - return value[: -len(unit)], INFERRED_UNITS.get(unit, unit.strip()) + return value.removesuffix(unit), INFERRED_UNITS.get(unit, unit.strip()) return value, None diff --git a/homeassistant/components/apple_tv/__init__.py b/homeassistant/components/apple_tv/__init__.py index 2c9ad84ac42..f2e341d4ab4 100644 --- a/homeassistant/components/apple_tv/__init__.py +++ b/homeassistant/components/apple_tv/__init__.py @@ -344,12 +344,7 @@ class AppleTVManager: ATTR_MANUFACTURER: "Apple", ATTR_NAME: self.config_entry.data[CONF_NAME], } - - area = attrs[ATTR_NAME] - name_trailer = f" {DEFAULT_NAME}" - if area.endswith(name_trailer): - area = area[: -len(name_trailer)] - attrs[ATTR_SUGGESTED_AREA] = area + attrs[ATTR_SUGGESTED_AREA] = attrs[ATTR_NAME].removesuffix(f" {DEFAULT_NAME}") if self.atv: dev_info = self.atv.device_info diff --git a/homeassistant/components/august/entity.py b/homeassistant/components/august/entity.py index 209747da0be..8dab470376b 100644 --- a/homeassistant/components/august/entity.py +++ b/homeassistant/components/august/entity.py @@ -70,7 +70,5 @@ def _remove_device_types(name, device_types): """ lower_name = name.lower() for device_type in device_types: - device_type_with_space = f" {device_type}" - if lower_name.endswith(device_type_with_space): - lower_name = lower_name[: -len(device_type_with_space)] + lower_name = lower_name.removesuffix(f" {device_type}") return name[: len(lower_name)] diff --git a/homeassistant/components/bosch_shc/config_flow.py b/homeassistant/components/bosch_shc/config_flow.py index 7cc4527a64f..b18fd65455c 100644 --- a/homeassistant/components/bosch_shc/config_flow.py +++ b/homeassistant/components/bosch_shc/config_flow.py @@ -198,7 +198,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): self.host = discovery_info.host local_name = discovery_info.hostname[:-1] - node_name = local_name[: -len(".local")] + node_name = local_name.removesuffix(".local") await self.async_set_unique_id(self.info["unique_id"]) self._abort_if_unique_id_configured({CONF_HOST: self.host}) diff --git a/homeassistant/components/denon/media_player.py b/homeassistant/components/denon/media_player.py index c1f864c8c2f..60da3df393e 100644 --- a/homeassistant/components/denon/media_player.py +++ b/homeassistant/components/denon/media_player.py @@ -110,14 +110,14 @@ class DenonDevice(MediaPlayerEntity): def _setup_sources(self, telnet): # NSFRN - Network name - nsfrn = self.telnet_request(telnet, "NSFRN ?")[len("NSFRN ") :] + nsfrn = self.telnet_request(telnet, "NSFRN ?").removeprefix("NSFRN ") if nsfrn: self._name = nsfrn # SSFUN - Configured sources with (optional) names self._source_list = {} for line in self.telnet_request(telnet, "SSFUN ?", all_lines=True): - ssfun = line[len("SSFUN") :].split(" ", 1) + ssfun = line.removeprefix("SSFUN").split(" ", 1) source = ssfun[0] if len(ssfun) == 2 and ssfun[1]: @@ -130,7 +130,7 @@ class DenonDevice(MediaPlayerEntity): # SSSOD - Deleted sources for line in self.telnet_request(telnet, "SSSOD ?", all_lines=True): - source, status = line[len("SSSOD") :].split(" ", 1) + source, status = line.removeprefix("SSSOD").split(" ", 1) if status == "DEL": for pretty_name, name in self._source_list.items(): if source == name: @@ -184,9 +184,9 @@ class DenonDevice(MediaPlayerEntity): self._volume_max = int(line[len("MVMAX ") : len("MVMAX XX")]) continue if line.startswith("MV"): - self._volume = int(line[len("MV") :]) + self._volume = int(line.removeprefix("MV")) self._muted = self.telnet_request(telnet, "MU?") == "MUON" - self._mediasource = self.telnet_request(telnet, "SI?")[len("SI") :] + self._mediasource = self.telnet_request(telnet, "SI?").removeprefix("SI") if self._mediasource in MEDIA_MODES.values(): self._mediainfo = "" @@ -202,7 +202,7 @@ class DenonDevice(MediaPlayerEntity): "NSE8", ] for line in self.telnet_request(telnet, "NSE", all_lines=True): - self._mediainfo += f"{line[len(answer_codes.pop(0)) :]}\n" + self._mediainfo += f"{line.removeprefix(answer_codes.pop(0))}\n" else: self._mediainfo = self.source diff --git a/homeassistant/components/doorbird/config_flow.py b/homeassistant/components/doorbird/config_flow.py index 678340c0259..4ad5e24247e 100644 --- a/homeassistant/components/doorbird/config_flow.py +++ b/homeassistant/components/doorbird/config_flow.py @@ -117,9 +117,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): return self.async_abort(reason="not_doorbird_device") chop_ending = "._axis-video._tcp.local." - friendly_hostname = discovery_info.name - if friendly_hostname.endswith(chop_ending): - friendly_hostname = friendly_hostname[: -len(chop_ending)] + friendly_hostname = discovery_info.name.removesuffix(chop_ending) self.context["title_placeholders"] = { CONF_NAME: friendly_hostname, diff --git a/homeassistant/components/esphome/config_flow.py b/homeassistant/components/esphome/config_flow.py index de9d3ebc624..0108b723276 100644 --- a/homeassistant/components/esphome/config_flow.py +++ b/homeassistant/components/esphome/config_flow.py @@ -179,7 +179,7 @@ class EsphomeFlowHandler(ConfigFlow, domain=DOMAIN): mac_address = format_mac(mac_address) # Hostname is format: livingroom.local. - self._name = discovery_info.hostname[: -len(".local.")] + self._name = discovery_info.hostname.removesuffix(".local.") self._device_name = self._name self._host = discovery_info.host self._port = discovery_info.port diff --git a/homeassistant/components/flux_led/__init__.py b/homeassistant/components/flux_led/__init__.py index 04d60fec25e..7d7ef2d42bf 100644 --- a/homeassistant/components/flux_led/__init__.py +++ b/homeassistant/components/flux_led/__init__.py @@ -111,7 +111,7 @@ async def _async_migrate_unique_ids(hass: HomeAssistant, entry: ConfigEntry) -> new_unique_id = None if entity_unique_id.startswith(entry_id): # Old format {entry_id}....., New format {unique_id}.... - new_unique_id = f"{unique_id}{entity_unique_id[len(entry_id):]}" + new_unique_id = f"{unique_id}{entity_unique_id.removeprefix(entry_id)}" elif ( ":" in entity_mac and entity_mac != unique_id diff --git a/homeassistant/components/frontend/__init__.py b/homeassistant/components/frontend/__init__.py index eff8bc77a9a..750801f3ddf 100644 --- a/homeassistant/components/frontend/__init__.py +++ b/homeassistant/components/frontend/__init__.py @@ -702,7 +702,7 @@ async def websocket_get_version( for req in integration.requirements: if req.startswith("home-assistant-frontend=="): - frontend = req.split("==", 1)[1] + frontend = req.removeprefix("home-assistant-frontend==") if frontend is None: connection.send_error(msg["id"], "unknown_version", "Version not found") diff --git a/homeassistant/components/google_assistant/logbook.py b/homeassistant/components/google_assistant/logbook.py index ac12ae2cb8c..9559188cbd2 100644 --- a/homeassistant/components/google_assistant/logbook.py +++ b/homeassistant/components/google_assistant/logbook.py @@ -17,9 +17,7 @@ def async_describe_events(hass, async_describe_event): commands = [] for command_payload in event.data["execution"]: - command = command_payload["command"] - if command.startswith(COMMON_COMMAND_PREFIX): - command = command[len(COMMON_COMMAND_PREFIX) :] + command = command_payload["command"].removeprefix(COMMON_COMMAND_PREFIX) commands.append(command) message = f"sent command {', '.join(commands)}" diff --git a/homeassistant/components/huawei_lte/__init__.py b/homeassistant/components/huawei_lte/__init__.py index 2b9be2efc97..badf7d0a484 100644 --- a/homeassistant/components/huawei_lte/__init__.py +++ b/homeassistant/components/huawei_lte/__init__.py @@ -365,9 +365,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: ): if not entity_entry.unique_id.startswith("None-"): continue - new_unique_id = ( - f"{serial_number}-{entity_entry.unique_id.split('-', 1)[1]}" - ) + new_unique_id = entity_entry.unique_id.removeprefix("None-") + new_unique_id = f"{serial_number}-{new_unique_id}" ent_reg.async_update_entity( entity_entry.entity_id, new_unique_id=new_unique_id ) diff --git a/homeassistant/components/hunterdouglas_powerview/config_flow.py b/homeassistant/components/hunterdouglas_powerview/config_flow.py index 1666db27d86..7c9bdfcf244 100644 --- a/homeassistant/components/hunterdouglas_powerview/config_flow.py +++ b/homeassistant/components/hunterdouglas_powerview/config_flow.py @@ -97,9 +97,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): ) -> FlowResult: """Handle zeroconf discovery.""" self.discovered_ip = discovery_info.host - name = discovery_info.name - if name.endswith(POWERVIEW_SUFFIX): - name = name[: -len(POWERVIEW_SUFFIX)] + name = discovery_info.name.removesuffix(POWERVIEW_SUFFIX) self.discovered_name = name return await self.async_step_discovery_confirm() @@ -108,9 +106,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): ) -> FlowResult: """Handle HomeKit discovery.""" self.discovered_ip = discovery_info.host - name = discovery_info.name - if name.endswith(HAP_SUFFIX): - name = name[: -len(HAP_SUFFIX)] + name = discovery_info.name.removesuffix(HAP_SUFFIX) self.discovered_name = name return await self.async_step_discovery_confirm() diff --git a/homeassistant/components/hyperion/camera.py b/homeassistant/components/hyperion/camera.py index a9d78a256d6..0366816ef1a 100644 --- a/homeassistant/components/hyperion/camera.py +++ b/homeassistant/components/hyperion/camera.py @@ -165,7 +165,7 @@ class HyperionCamera(Camera): async with self._image_cond: try: self._image = base64.b64decode( - img_data[len(IMAGE_STREAM_JPG_SENTINEL) :] + img_data.removeprefix(IMAGE_STREAM_JPG_SENTINEL) ) except binascii.Error: return diff --git a/homeassistant/components/isy994/config_flow.py b/homeassistant/components/isy994/config_flow.py index 908bf710bf4..0b61b14d9b1 100644 --- a/homeassistant/components/isy994/config_flow.py +++ b/homeassistant/components/isy994/config_flow.py @@ -234,10 +234,8 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): assert isinstance(url, str) parsed_url = urlparse(url) mac = discovery_info.upnp[ssdp.ATTR_UPNP_UDN] - if mac.startswith(UDN_UUID_PREFIX): - mac = mac[len(UDN_UUID_PREFIX) :] - if url.endswith(ISY_URL_POSTFIX): - url = url[: -len(ISY_URL_POSTFIX)] + mac = mac.removeprefix(UDN_UUID_PREFIX) + url = url.removesuffix(ISY_URL_POSTFIX) port = HTTP_PORT if parsed_url.port: diff --git a/homeassistant/components/kodi/config_flow.py b/homeassistant/components/kodi/config_flow.py index e39a791a11b..ea1cf91b4c8 100644 --- a/homeassistant/components/kodi/config_flow.py +++ b/homeassistant/components/kodi/config_flow.py @@ -106,7 +106,7 @@ class KodiConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): """Handle zeroconf discovery.""" self._host = discovery_info.host self._port = discovery_info.port or DEFAULT_PORT - self._name = discovery_info.hostname[: -len(".local.")] + self._name = discovery_info.hostname.removesuffix(".local.") if not (uuid := discovery_info.properties.get("uuid")): return self.async_abort(reason="no_uuid") diff --git a/homeassistant/components/lookin/config_flow.py b/homeassistant/components/lookin/config_flow.py index 2b4df9cc027..016ffbd17f5 100644 --- a/homeassistant/components/lookin/config_flow.py +++ b/homeassistant/components/lookin/config_flow.py @@ -31,7 +31,7 @@ class LookinFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): self, discovery_info: zeroconf.ZeroconfServiceInfo ) -> FlowResult: """Start a discovery flow from zeroconf.""" - uid: str = discovery_info.hostname[: -len(".local.")] + uid: str = discovery_info.hostname.removesuffix(".local.") host: str = discovery_info.host await self.async_set_unique_id(uid.upper()) self._abort_if_unique_id_configured(updates={CONF_HOST: host}) diff --git a/homeassistant/components/plex/services.py b/homeassistant/components/plex/services.py index cb88e98257d..b5080dd2c5c 100644 --- a/homeassistant/components/plex/services.py +++ b/homeassistant/components/plex/services.py @@ -118,7 +118,7 @@ def process_plex_payload( if content_id.startswith(PLEX_URI_SCHEME + "{"): # Handle the special payload of 'plex://{}' - content_id = content_id[len(PLEX_URI_SCHEME) :] + content_id = content_id.removeprefix(PLEX_URI_SCHEME) content = json.loads(content_id) elif content_id.startswith(PLEX_URI_SCHEME): # Handle standard media_browser payloads diff --git a/homeassistant/components/recorder/util.py b/homeassistant/components/recorder/util.py index f0c9d555a9d..02ec644dd9e 100644 --- a/homeassistant/components/recorder/util.py +++ b/homeassistant/components/recorder/util.py @@ -225,7 +225,7 @@ def validate_or_move_away_sqlite_database(dburl: str) -> bool: def dburl_to_path(dburl: str) -> str: """Convert the db url into a filesystem path.""" - return dburl[len(SQLITE_URL_PREFIX) :] + return dburl.removeprefix(SQLITE_URL_PREFIX) def last_run_was_recently_clean(cursor: CursorFetchStrategy) -> bool: diff --git a/homeassistant/components/sonos/helpers.py b/homeassistant/components/sonos/helpers.py index f1805eda054..69fdf817bd5 100644 --- a/homeassistant/components/sonos/helpers.py +++ b/homeassistant/components/sonos/helpers.py @@ -115,9 +115,9 @@ def _find_target_identifier(instance: Any, fallback_soco: SoCo | None) -> str | def hostname_to_uid(hostname: str) -> str: """Convert a Sonos hostname to a uid.""" if hostname.startswith("Sonos-"): - baseuid = hostname.split("-")[1].replace(".local.", "") + baseuid = hostname.removeprefix("Sonos-").replace(".local.", "") elif hostname.startswith("sonos"): - baseuid = hostname[5:].replace(".local.", "") + baseuid = hostname.removeprefix("sonos").replace(".local.", "") else: raise ValueError(f"{hostname} is not a sonos device.") return f"{UID_PREFIX}{baseuid}{UID_POSTFIX}" diff --git a/homeassistant/components/spotify/browse_media.py b/homeassistant/components/spotify/browse_media.py index 12268c8ab56..0f72d459b68 100644 --- a/homeassistant/components/spotify/browse_media.py +++ b/homeassistant/components/spotify/browse_media.py @@ -216,7 +216,7 @@ async def async_browse_media_internal( # Strip prefix if media_content_type: - media_content_type = media_content_type[len(MEDIA_PLAYER_PREFIX) :] + media_content_type = media_content_type.removeprefix(MEDIA_PLAYER_PREFIX) payload = { "media_content_type": media_content_type, diff --git a/homeassistant/components/spotify/media_player.py b/homeassistant/components/spotify/media_player.py index d09b2795e88..1145686efe7 100644 --- a/homeassistant/components/spotify/media_player.py +++ b/homeassistant/components/spotify/media_player.py @@ -300,8 +300,7 @@ class SpotifyMediaPlayer(MediaPlayerEntity): @spotify_exception_handler def play_media(self, media_type: str, media_id: str, **kwargs: Any) -> None: """Play media.""" - if media_type.startswith(MEDIA_PLAYER_PREFIX): - media_type = media_type[len(MEDIA_PLAYER_PREFIX) :] + media_type = media_type.removeprefix(MEDIA_PLAYER_PREFIX) kwargs = {} diff --git a/homeassistant/components/spotify/util.py b/homeassistant/components/spotify/util.py index 7f7f682fb9e..e9af305a1d0 100644 --- a/homeassistant/components/spotify/util.py +++ b/homeassistant/components/spotify/util.py @@ -15,7 +15,7 @@ def is_spotify_media_type(media_content_type: str) -> bool: def resolve_spotify_media_type(media_content_type: str) -> str: """Return actual spotify media_content_type.""" - return media_content_type[len(MEDIA_PLAYER_PREFIX) :] + return media_content_type.removeprefix(MEDIA_PLAYER_PREFIX) def fetch_image_url(item: dict[str, Any], key="images") -> str | None: diff --git a/homeassistant/components/zha/config_flow.py b/homeassistant/components/zha/config_flow.py index 165fb04a054..8f4c9ee4336 100644 --- a/homeassistant/components/zha/config_flow.py +++ b/homeassistant/components/zha/config_flow.py @@ -518,7 +518,7 @@ class ZhaConfigFlowHandler(BaseZhaFlow, config_entries.ConfigFlow, domain=DOMAIN else: self._radio_mgr.radio_type = RadioType.znp - node_name = local_name[: -len(".local")] + node_name = local_name.removesuffix(".local") device_path = f"socket://{discovery_info.host}:{port}" await self._set_unique_id_or_update_path(