Make use of str.removeprefix and .removesuffix (#85584)

This commit is contained in:
Ville Skyttä 2023-01-13 13:19:38 +02:00 committed by GitHub
parent d44210e573
commit ae302bbec0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
24 changed files with 33 additions and 52 deletions

View File

@ -45,7 +45,7 @@ async def _async_migrate_unique_ids(
entity_unique_id = entity_entry.unique_id entity_unique_id = entity_entry.unique_id
if entity_unique_id.startswith(entry_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( _LOGGER.debug(
"Migrating unique_id from [%s] to [%s]", "Migrating unique_id from [%s] to [%s]",
entity_unique_id, entity_unique_id,

View File

@ -474,7 +474,7 @@ def infer_unit(value: str) -> tuple[str, str | None]:
for unit in ALL_UNITS: for unit in ALL_UNITS:
if value.endswith(unit): 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 return value, None

View File

@ -344,12 +344,7 @@ class AppleTVManager:
ATTR_MANUFACTURER: "Apple", ATTR_MANUFACTURER: "Apple",
ATTR_NAME: self.config_entry.data[CONF_NAME], ATTR_NAME: self.config_entry.data[CONF_NAME],
} }
attrs[ATTR_SUGGESTED_AREA] = attrs[ATTR_NAME].removesuffix(f" {DEFAULT_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
if self.atv: if self.atv:
dev_info = self.atv.device_info dev_info = self.atv.device_info

View File

@ -70,7 +70,5 @@ def _remove_device_types(name, device_types):
""" """
lower_name = name.lower() lower_name = name.lower()
for device_type in device_types: for device_type in device_types:
device_type_with_space = f" {device_type}" lower_name = lower_name.removesuffix(f" {device_type}")
if lower_name.endswith(device_type_with_space):
lower_name = lower_name[: -len(device_type_with_space)]
return name[: len(lower_name)] return name[: len(lower_name)]

View File

@ -198,7 +198,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
self.host = discovery_info.host self.host = discovery_info.host
local_name = discovery_info.hostname[:-1] 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"]) await self.async_set_unique_id(self.info["unique_id"])
self._abort_if_unique_id_configured({CONF_HOST: self.host}) self._abort_if_unique_id_configured({CONF_HOST: self.host})

View File

@ -110,14 +110,14 @@ class DenonDevice(MediaPlayerEntity):
def _setup_sources(self, telnet): def _setup_sources(self, telnet):
# NSFRN - Network name # NSFRN - Network name
nsfrn = self.telnet_request(telnet, "NSFRN ?")[len("NSFRN ") :] nsfrn = self.telnet_request(telnet, "NSFRN ?").removeprefix("NSFRN ")
if nsfrn: if nsfrn:
self._name = nsfrn self._name = nsfrn
# SSFUN - Configured sources with (optional) names # SSFUN - Configured sources with (optional) names
self._source_list = {} self._source_list = {}
for line in self.telnet_request(telnet, "SSFUN ?", all_lines=True): 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] source = ssfun[0]
if len(ssfun) == 2 and ssfun[1]: if len(ssfun) == 2 and ssfun[1]:
@ -130,7 +130,7 @@ class DenonDevice(MediaPlayerEntity):
# SSSOD - Deleted sources # SSSOD - Deleted sources
for line in self.telnet_request(telnet, "SSSOD ?", all_lines=True): 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": if status == "DEL":
for pretty_name, name in self._source_list.items(): for pretty_name, name in self._source_list.items():
if source == name: if source == name:
@ -184,9 +184,9 @@ class DenonDevice(MediaPlayerEntity):
self._volume_max = int(line[len("MVMAX ") : len("MVMAX XX")]) self._volume_max = int(line[len("MVMAX ") : len("MVMAX XX")])
continue continue
if line.startswith("MV"): 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._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(): if self._mediasource in MEDIA_MODES.values():
self._mediainfo = "" self._mediainfo = ""
@ -202,7 +202,7 @@ class DenonDevice(MediaPlayerEntity):
"NSE8", "NSE8",
] ]
for line in self.telnet_request(telnet, "NSE", all_lines=True): 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: else:
self._mediainfo = self.source self._mediainfo = self.source

View File

@ -117,9 +117,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
return self.async_abort(reason="not_doorbird_device") return self.async_abort(reason="not_doorbird_device")
chop_ending = "._axis-video._tcp.local." chop_ending = "._axis-video._tcp.local."
friendly_hostname = discovery_info.name friendly_hostname = discovery_info.name.removesuffix(chop_ending)
if friendly_hostname.endswith(chop_ending):
friendly_hostname = friendly_hostname[: -len(chop_ending)]
self.context["title_placeholders"] = { self.context["title_placeholders"] = {
CONF_NAME: friendly_hostname, CONF_NAME: friendly_hostname,

View File

@ -179,7 +179,7 @@ class EsphomeFlowHandler(ConfigFlow, domain=DOMAIN):
mac_address = format_mac(mac_address) mac_address = format_mac(mac_address)
# Hostname is format: livingroom.local. # 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._device_name = self._name
self._host = discovery_info.host self._host = discovery_info.host
self._port = discovery_info.port self._port = discovery_info.port

View File

@ -111,7 +111,7 @@ async def _async_migrate_unique_ids(hass: HomeAssistant, entry: ConfigEntry) ->
new_unique_id = None new_unique_id = None
if entity_unique_id.startswith(entry_id): if entity_unique_id.startswith(entry_id):
# Old format {entry_id}....., New format {unique_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 ( elif (
":" in entity_mac ":" in entity_mac
and entity_mac != unique_id and entity_mac != unique_id

View File

@ -702,7 +702,7 @@ async def websocket_get_version(
for req in integration.requirements: for req in integration.requirements:
if req.startswith("home-assistant-frontend=="): if req.startswith("home-assistant-frontend=="):
frontend = req.split("==", 1)[1] frontend = req.removeprefix("home-assistant-frontend==")
if frontend is None: if frontend is None:
connection.send_error(msg["id"], "unknown_version", "Version not found") connection.send_error(msg["id"], "unknown_version", "Version not found")

View File

@ -17,9 +17,7 @@ def async_describe_events(hass, async_describe_event):
commands = [] commands = []
for command_payload in event.data["execution"]: for command_payload in event.data["execution"]:
command = command_payload["command"] command = command_payload["command"].removeprefix(COMMON_COMMAND_PREFIX)
if command.startswith(COMMON_COMMAND_PREFIX):
command = command[len(COMMON_COMMAND_PREFIX) :]
commands.append(command) commands.append(command)
message = f"sent command {', '.join(commands)}" message = f"sent command {', '.join(commands)}"

View File

@ -365,9 +365,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
): ):
if not entity_entry.unique_id.startswith("None-"): if not entity_entry.unique_id.startswith("None-"):
continue continue
new_unique_id = ( new_unique_id = entity_entry.unique_id.removeprefix("None-")
f"{serial_number}-{entity_entry.unique_id.split('-', 1)[1]}" new_unique_id = f"{serial_number}-{new_unique_id}"
)
ent_reg.async_update_entity( ent_reg.async_update_entity(
entity_entry.entity_id, new_unique_id=new_unique_id entity_entry.entity_id, new_unique_id=new_unique_id
) )

View File

@ -97,9 +97,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
) -> FlowResult: ) -> FlowResult:
"""Handle zeroconf discovery.""" """Handle zeroconf discovery."""
self.discovered_ip = discovery_info.host self.discovered_ip = discovery_info.host
name = discovery_info.name name = discovery_info.name.removesuffix(POWERVIEW_SUFFIX)
if name.endswith(POWERVIEW_SUFFIX):
name = name[: -len(POWERVIEW_SUFFIX)]
self.discovered_name = name self.discovered_name = name
return await self.async_step_discovery_confirm() return await self.async_step_discovery_confirm()
@ -108,9 +106,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
) -> FlowResult: ) -> FlowResult:
"""Handle HomeKit discovery.""" """Handle HomeKit discovery."""
self.discovered_ip = discovery_info.host self.discovered_ip = discovery_info.host
name = discovery_info.name name = discovery_info.name.removesuffix(HAP_SUFFIX)
if name.endswith(HAP_SUFFIX):
name = name[: -len(HAP_SUFFIX)]
self.discovered_name = name self.discovered_name = name
return await self.async_step_discovery_confirm() return await self.async_step_discovery_confirm()

View File

@ -165,7 +165,7 @@ class HyperionCamera(Camera):
async with self._image_cond: async with self._image_cond:
try: try:
self._image = base64.b64decode( self._image = base64.b64decode(
img_data[len(IMAGE_STREAM_JPG_SENTINEL) :] img_data.removeprefix(IMAGE_STREAM_JPG_SENTINEL)
) )
except binascii.Error: except binascii.Error:
return return

View File

@ -234,10 +234,8 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
assert isinstance(url, str) assert isinstance(url, str)
parsed_url = urlparse(url) parsed_url = urlparse(url)
mac = discovery_info.upnp[ssdp.ATTR_UPNP_UDN] mac = discovery_info.upnp[ssdp.ATTR_UPNP_UDN]
if mac.startswith(UDN_UUID_PREFIX): mac = mac.removeprefix(UDN_UUID_PREFIX)
mac = mac[len(UDN_UUID_PREFIX) :] url = url.removesuffix(ISY_URL_POSTFIX)
if url.endswith(ISY_URL_POSTFIX):
url = url[: -len(ISY_URL_POSTFIX)]
port = HTTP_PORT port = HTTP_PORT
if parsed_url.port: if parsed_url.port:

View File

@ -106,7 +106,7 @@ class KodiConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle zeroconf discovery.""" """Handle zeroconf discovery."""
self._host = discovery_info.host self._host = discovery_info.host
self._port = discovery_info.port or DEFAULT_PORT 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")): if not (uuid := discovery_info.properties.get("uuid")):
return self.async_abort(reason="no_uuid") return self.async_abort(reason="no_uuid")

View File

@ -31,7 +31,7 @@ class LookinFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
self, discovery_info: zeroconf.ZeroconfServiceInfo self, discovery_info: zeroconf.ZeroconfServiceInfo
) -> FlowResult: ) -> FlowResult:
"""Start a discovery flow from zeroconf.""" """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 host: str = discovery_info.host
await self.async_set_unique_id(uid.upper()) await self.async_set_unique_id(uid.upper())
self._abort_if_unique_id_configured(updates={CONF_HOST: host}) self._abort_if_unique_id_configured(updates={CONF_HOST: host})

View File

@ -118,7 +118,7 @@ def process_plex_payload(
if content_id.startswith(PLEX_URI_SCHEME + "{"): if content_id.startswith(PLEX_URI_SCHEME + "{"):
# Handle the special payload of 'plex://{<json>}' # Handle the special payload of 'plex://{<json>}'
content_id = content_id[len(PLEX_URI_SCHEME) :] content_id = content_id.removeprefix(PLEX_URI_SCHEME)
content = json.loads(content_id) content = json.loads(content_id)
elif content_id.startswith(PLEX_URI_SCHEME): elif content_id.startswith(PLEX_URI_SCHEME):
# Handle standard media_browser payloads # Handle standard media_browser payloads

View File

@ -225,7 +225,7 @@ def validate_or_move_away_sqlite_database(dburl: str) -> bool:
def dburl_to_path(dburl: str) -> str: def dburl_to_path(dburl: str) -> str:
"""Convert the db url into a filesystem path.""" """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: def last_run_was_recently_clean(cursor: CursorFetchStrategy) -> bool:

View File

@ -115,9 +115,9 @@ def _find_target_identifier(instance: Any, fallback_soco: SoCo | None) -> str |
def hostname_to_uid(hostname: str) -> str: def hostname_to_uid(hostname: str) -> str:
"""Convert a Sonos hostname to a uid.""" """Convert a Sonos hostname to a uid."""
if hostname.startswith("Sonos-"): if hostname.startswith("Sonos-"):
baseuid = hostname.split("-")[1].replace(".local.", "") baseuid = hostname.removeprefix("Sonos-").replace(".local.", "")
elif hostname.startswith("sonos"): elif hostname.startswith("sonos"):
baseuid = hostname[5:].replace(".local.", "") baseuid = hostname.removeprefix("sonos").replace(".local.", "")
else: else:
raise ValueError(f"{hostname} is not a sonos device.") raise ValueError(f"{hostname} is not a sonos device.")
return f"{UID_PREFIX}{baseuid}{UID_POSTFIX}" return f"{UID_PREFIX}{baseuid}{UID_POSTFIX}"

View File

@ -216,7 +216,7 @@ async def async_browse_media_internal(
# Strip prefix # Strip prefix
if media_content_type: 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 = { payload = {
"media_content_type": media_content_type, "media_content_type": media_content_type,

View File

@ -300,8 +300,7 @@ class SpotifyMediaPlayer(MediaPlayerEntity):
@spotify_exception_handler @spotify_exception_handler
def play_media(self, media_type: str, media_id: str, **kwargs: Any) -> None: def play_media(self, media_type: str, media_id: str, **kwargs: Any) -> None:
"""Play media.""" """Play media."""
if media_type.startswith(MEDIA_PLAYER_PREFIX): media_type = media_type.removeprefix(MEDIA_PLAYER_PREFIX)
media_type = media_type[len(MEDIA_PLAYER_PREFIX) :]
kwargs = {} kwargs = {}

View File

@ -15,7 +15,7 @@ def is_spotify_media_type(media_content_type: str) -> bool:
def resolve_spotify_media_type(media_content_type: str) -> str: def resolve_spotify_media_type(media_content_type: str) -> str:
"""Return actual spotify media_content_type.""" """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: def fetch_image_url(item: dict[str, Any], key="images") -> str | None:

View File

@ -518,7 +518,7 @@ class ZhaConfigFlowHandler(BaseZhaFlow, config_entries.ConfigFlow, domain=DOMAIN
else: else:
self._radio_mgr.radio_type = RadioType.znp 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}" device_path = f"socket://{discovery_info.host}:{port}"
await self._set_unique_id_or_update_path( await self._set_unique_id_or_update_path(