Improve string formatting v2 (#33645)

* Improve string formatting v2

* Improve string formatting v3

* Address review comments
This commit is contained in:
springstan 2020-04-04 23:09:34 +02:00 committed by GitHub
parent d2e70eb967
commit dde93304d3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
28 changed files with 42 additions and 40 deletions

View File

@ -286,9 +286,9 @@ class AlmondAgent(conversation.AbstractConversationAgent):
buffer = ""
for message in response["messages"]:
if message["type"] == "text":
buffer += "\n" + message["text"]
buffer += f"\n{message['text']}"
elif message["type"] == "picture":
buffer += "\n Picture: " + message["url"]
buffer += f"\n Picture: {message['url']}"
elif message["type"] == "rdl":
buffer += (
"\n Link: "

View File

@ -186,4 +186,5 @@ class AnthemAVR(MediaPlayerDevice):
def dump_avrdata(self):
"""Return state of avr object for debugging forensics."""
attrs = vars(self)
return "dump_avrdata: " + ", ".join("%s: %s" % item for item in attrs.items())
items_string = ", ".join(f"{item}: {item}" for item in attrs.items())
return f"dump_avrdata: {items_string}"

View File

@ -129,8 +129,10 @@ async def scan_apple_tvs(hass):
if not devices:
devices = ["No device(s) found"]
found_devices = "<br /><br />".join(devices)
hass.components.persistent_notification.async_create(
"The following devices were found:<br /><br />" + "<br /><br />".join(devices),
f"The following devices were found:<br /><br />{found_devices}",
title=NOTIFICATION_SCAN_TITLE,
notification_id=NOTIFICATION_SCAN_ID,
)

View File

@ -1038,9 +1038,7 @@ class BluesoundPlayer(MediaPlayerDevice):
volume = 0
elif volume > 1:
volume = 1
return await self.send_bluesound_command(
"Volume?level=" + str(float(volume) * 100)
)
return await self.send_bluesound_command(f"Volume?level={float(volume) * 100}")
async def async_mute_volume(self, mute):
"""Send mute command to media player."""
@ -1050,5 +1048,5 @@ class BluesoundPlayer(MediaPlayerDevice):
self._lastvol = volume
return await self.send_bluesound_command("Volume?level=0")
return await self.send_bluesound_command(
"Volume?level=" + str(float(self._lastvol) * 100)
f"Volume?level={float(self._lastvol) * 100}"
)

View File

@ -257,11 +257,12 @@ class DenonDevice(MediaPlayerDevice):
def set_volume_level(self, volume):
"""Set volume level, range 0..1."""
self.telnet_command("MV" + str(round(volume * self._volume_max)).zfill(2))
self.telnet_command(f"MV{str(round(volume * self._volume_max)).zfill(2)}")
def mute_volume(self, mute):
"""Mute (true) or unmute (false) media player."""
self.telnet_command("MU" + ("ON" if mute else "OFF"))
mute_status = "ON" if mute else "OFF"
self.telnet_command(f"MU{mute_status})")
def media_play(self):
"""Play media player."""
@ -289,4 +290,4 @@ class DenonDevice(MediaPlayerDevice):
def select_source(self, source):
"""Select input source."""
self.telnet_command("SI" + self._source_list.get(source))
self.telnet_command(f"SI{self._source_list.get(source)}")

View File

@ -241,7 +241,7 @@ class EnturPublicTransportSensor(Entity):
return
for i, call in enumerate(calls[2:]):
key_name = "departure_#" + str(i + 3)
key_name = f"departure_#{i + 3}"
self._attributes[key_name] = (
f"{'' if bool(call.is_realtime) else 'ca. '}"
f"{call.expected_departure_time.strftime('%H:%M')} {call.front_display}"

View File

@ -163,7 +163,7 @@ class Itunes:
if found_playlists:
playlist = found_playlists[0]
path = "/playlists/" + playlist["id"] + "/play"
path = f"/playlists/{playlist['id']}/play"
return self._request("PUT", path)
def artwork_url(self):
@ -324,7 +324,7 @@ class ItunesDevice(MediaPlayerDevice):
self.player_state in (STATE_PLAYING, STATE_IDLE, STATE_PAUSED)
and self.current_title is not None
):
return self.client.artwork_url() + "?id=" + self.content_id
return f"{self.client.artwork_url()}?id={self.content_id}"
return (
"https://cloud.githubusercontent.com/assets/260/9829355"

View File

@ -214,7 +214,7 @@ class Life360Scanner:
err_msg = member["issues"]["title"]
if err_msg:
if member["issues"]["dialog"]:
err_msg += ": " + member["issues"]["dialog"]
err_msg += f": {member['issues']['dialog']}"
else:
err_msg = "Location information missing"
self._err(dev_id, err_msg)

View File

@ -159,4 +159,4 @@ class LinkySensor(Entity):
year_index = INDEX_CURRENT
if self._time.endswith("Dec"):
year_index = INDEX_LAST
self._time += " " + self._account.data[YEARLY][year_index][TIME]
self._time += f" {self._account.data[YEARLY][year_index][TIME]}"

View File

@ -157,9 +157,9 @@ def parse_species(species_data):
species_dict["code"] = species["@SpeciesCode"]
species_dict["quality"] = species["@AirQualityBand"]
species_dict["index"] = species["@AirQualityIndex"]
species_dict["summary"] = (
species_dict["code"] + " is " + species_dict["quality"]
)
species_dict[
"summary"
] = f"{species_dict['code']} is {species_dict['quality']}"
parsed_species_data.append(species_dict)
quality_list.append(species_dict["quality"])
return parsed_species_data, quality_list

View File

@ -246,7 +246,7 @@ class ModbusRegisterSensor(RestoreEntity):
if isinstance(val, int):
self._value = str(val)
if self._precision > 0:
self._value += "." + "0" * self._precision
self._value += f".{'0' * self._precision}"
else:
self._value = f"{val:.{self._precision}f}"

View File

@ -208,7 +208,7 @@ class NeatoConnectedVacuum(StateVacuumDevice):
and "name" in self._state["cleaning"]["boundary"]
):
self._status_state += (
" " + self._state["cleaning"]["boundary"]["name"]
f" {self._state['cleaning']['boundary']['name']}"
)
else:
self._status_state = robot_alert

View File

@ -210,7 +210,7 @@ class OneWire(Entity):
def __init__(self, name, device_file, sensor_type):
"""Initialize the sensor."""
self._name = name + " " + sensor_type.capitalize()
self._name = f"{name} {sensor_type.capitalize()}"
self._device_file = device_file
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
self._state = None

View File

@ -142,7 +142,7 @@ class PioneerDevice(MediaPlayerDevice):
# Build the source name dictionaries if necessary
if not self._source_name_to_number:
for i in range(MAX_SOURCE_NUMBERS):
result = self.telnet_request(telnet, "?RGB" + str(i).zfill(2), "RGB")
result = self.telnet_request(telnet, f"?RGB{str(i).zfill(2)}", "RGB")
if not result:
continue

View File

@ -106,8 +106,8 @@ class I2CHatSwitch(ToggleEntity):
def _log_message(self, message):
"""Create log message."""
string = self._name + " "
string += self._board + "I2CHat@" + hex(self._address) + " "
string += "channel:" + str(self._channel) + message
string += f"{self._board}I2CHat@{hex(self._address)} "
string += f"channel:{str(self._channel)}{message}"
return string
@property

View File

@ -76,7 +76,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
if not isinstance(event, SensorEvent):
return
device_id = "sensor_" + slugify(event.device.id_string.lower())
device_id = f"sensor_{slugify(event.device.id_string.lower())}"
if device_id in RFX_DEVICES:
sensors = RFX_DEVICES[device_id]

View File

@ -98,7 +98,7 @@ class ThinkingCleanerSwitch(ToggleEntity):
@property
def name(self):
"""Return the name of the sensor."""
return self._tc_object.name + " " + SWITCH_TYPES[self.type][0]
return f"{self._tc_object.name} {SWITCH_TYPES[self.type][0]}"
@property
def is_on(self):

View File

@ -316,7 +316,7 @@ class TraccarScanner:
None,
)
self._hass.bus.async_fire(
"traccar_" + self._event_types.get(event["type"]),
f"traccar_{self._event_types.get(event['type'])}",
{
"device_traccar_id": event["deviceId"],
"device_name": device_name,

View File

@ -749,7 +749,7 @@ class WinkDevice(Entity):
self.schedule_update_ha_state()
except (ValueError, KeyError, AttributeError):
_LOGGER.error(
"Error in pubnub JSON for %s polling API for current state", self.name,
"Error in pubnub JSON for %s polling API for current state", self.name
)
self.schedule_update_ha_state(True)
@ -912,7 +912,7 @@ class WinkNimbusDialDevice(WinkDevice):
@property
def name(self):
"""Return the name of the device."""
return self.parent.name() + " dial " + str(self.wink.index() + 1)
return f"{self.parent.name()} dial {self.wink.index() + 1}"
@property
def device_state_attributes(self):

View File

@ -329,7 +329,7 @@ class WUAlertsSensorConfig(WUSensorConfig):
for alert in ALERTS_ATTRS:
if data[alert]:
if multiple_alerts:
dkey = alert.capitalize() + "_" + data["type"]
dkey = f"{alert.capitalize()}_{data['type']}"
else:
dkey = alert.capitalize()
attrs[dkey] = data[alert]

View File

@ -100,12 +100,12 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
if DATA_KEY not in hass.data:
hass.data[DATA_KEY] = {}
friendly_name = config.get(CONF_NAME, "xiaomi_miio_" + host.replace(".", "_"))
friendly_name = config.get(CONF_NAME, f"xiaomi_miio_{host.replace('.', '_')}")
slot = config.get(CONF_SLOT)
timeout = config.get(CONF_TIMEOUT)
xiaomi_miio_remote = XiaomiMiioRemote(
friendly_name, device, unique_id, slot, timeout, config.get(CONF_COMMANDS),
friendly_name, device, unique_id, slot, timeout, config.get(CONF_COMMANDS)
)
hass.data[DATA_KEY][host] = xiaomi_miio_remote

View File

@ -233,7 +233,7 @@ class YamahaDevice(MediaPlayerDevice):
zone_name = self._zone_names.get(self._zone, self._zone)
if zone_name != "Main_Zone":
# Zone will be one of Main_Zone, Zone_2, Zone_3
name += " " + zone_name.replace("_", " ")
name += f" {zone_name.replace('_', ' ')}"
return name
@property

View File

@ -608,7 +608,7 @@ class ZHADevice(LogMixin):
cluster_binding.id,
group_id,
)
zdo.debug("processing " + op_msg, *op_params)
zdo.debug(f"processing {op_msg}", *op_params)
tasks.append(
(
zdo.request(

View File

@ -186,7 +186,7 @@ def check(config_dir, secrets=False):
continue
# The * in the key is removed to find the mock_function (side_effect)
# This allows us to use one side_effect to patch multiple locations
mock_function = locals()["mock_" + key.replace("*", "")]
mock_function = locals()[f"mock_{key.replace('*', '')}"]
PATCHES[key] = patch(val[0], side_effect=mock_function)
# Start all patches

View File

@ -52,7 +52,7 @@ def generate_and_validate(integrations: Dict[str, Integration]):
"homeassistant/components/{}/* {}".format(domain, " ".join(codeowners))
)
parts.append("\n" + INDIVIDUAL_FILES.strip())
parts.append(f"\n{INDIVIDUAL_FILES.strip()}")
return "\n".join(parts)

View File

@ -52,7 +52,7 @@ def main():
add_msg(
f"CONFIG_SCHEMA {schema_type}",
module_name + " " + color("cyan", str(schema)[:60]),
f"{module_name} {color('cyan', str(schema)[:60])}",
)
for key in sorted(msg):

View File

@ -105,7 +105,7 @@ def app_fixture(hass, config_file):
app.app_type = "WEBHOOK_SMART_APP"
app.classifications = [CLASSIFICATION_AUTOMATION]
app.display_name = "Home Assistant"
app.description = hass.config.location_name + " at " + hass.config.api.base_url
app.description = f"{hass.config.location_name} at {hass.config.api.base_url}"
app.single_instance = True
app.webhook_target_url = webhook.async_generate_url(
hass, hass.data[DOMAIN][CONF_WEBHOOK_ID]

View File

@ -146,7 +146,7 @@ async def find_entity_id(domain, zha_device, hass):
machine so that we can test state changes.
"""
ieeetail = "".join([f"{o:02x}" for o in zha_device.ieee[:4]])
head = f"{domain}." + slugify(f"{zha_device.name} {ieeetail}")
head = f"{domain}.{slugify(f'{zha_device.name} {ieeetail}')}"
enitiy_ids = hass.states.async_entity_ids(domain)
await hass.async_block_till_done()