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
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,

View file

@ -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

View file

@ -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

View file

@ -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)]

View file

@ -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})

View file

@ -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

View file

@ -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,

View file

@ -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

View file

@ -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

View file

@ -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")

View file

@ -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)}"

View file

@ -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
)

View file

@ -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()

View file

@ -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

View file

@ -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:

View file

@ -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")

View file

@ -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})

View file

@ -118,7 +118,7 @@ def process_plex_payload(
if content_id.startswith(PLEX_URI_SCHEME + "{"):
# 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)
elif content_id.startswith(PLEX_URI_SCHEME):
# 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:
"""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:

View file

@ -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}"

View file

@ -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,

View file

@ -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 = {}

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:
"""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:

View file

@ -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(