Improve string formatting v4 (#33668)

* Improve string formatting v4

* Use normal strings instead of f-strings

* Fix zeroconf test by adding back part of a condition
This commit is contained in:
springstan 2020-04-05 16:01:41 +02:00 committed by GitHub
parent b855177fe6
commit e3bcfb88e7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 43 additions and 47 deletions

View File

@ -291,10 +291,8 @@ class AlmondAgent(conversation.AbstractConversationAgent):
buffer += f"\n Picture: {message['url']}" buffer += f"\n Picture: {message['url']}"
elif message["type"] == "rdl": elif message["type"] == "rdl":
buffer += ( buffer += (
"\n Link: " f"\n Link: {message['rdl']['displayTitle']} "
+ message["rdl"]["displayTitle"] f"{message['rdl']['webCallback']}"
+ " "
+ message["rdl"]["webCallback"]
) )
elif message["type"] == "choice": elif message["type"] == "choice":
if first_choice: if first_choice:

View File

@ -142,9 +142,8 @@ class AnthemAVR(MediaPlayerDevice):
def app_name(self): def app_name(self):
"""Return details about current video and audio stream.""" """Return details about current video and audio stream."""
return ( return (
self._lookup("video_input_resolution_text", "") f"{self._lookup('video_input_resolution_text', '')} "
+ " " f"{self._lookup('audio_input_name', '')}"
+ self._lookup("audio_input_name", "")
) )
@property @property

View File

@ -154,8 +154,10 @@ def request_configuration(config, hass, add_entities):
_CONFIGURING[host] = configurator.request_config( _CONFIGURING[host] = configurator.request_config(
name, name,
bravia_configuration_callback, bravia_configuration_callback,
description="Enter the Pin shown on your Sony Bravia TV." description=(
+ "If no Pin is shown, enter 0000 to let TV show you a Pin.", "Enter the Pin shown on your Sony Bravia TV."
"If no Pin is shown, enter 0000 to let TV show you a Pin."
),
description_image="/static/images/smart-tv.png", description_image="/static/images/smart-tv.png",
submit_caption="Confirm", submit_caption="Confirm",
fields=[{"id": "pin", "name": "Enter the pin", "type": ""}], fields=[{"id": "pin", "name": "Enter the pin", "type": ""}],

View File

@ -46,7 +46,7 @@ class EnvisalinkSensor(EnvisalinkDevice, Entity):
self._partition_number = partition_number self._partition_number = partition_number
_LOGGER.debug("Setting up sensor for partition: %s", partition_name) _LOGGER.debug("Setting up sensor for partition: %s", partition_name)
super().__init__(partition_name + " Keypad", info, controller) super().__init__(f"{partition_name} Keypad", info, controller)
async def async_added_to_hass(self): async def async_added_to_hass(self):
"""Register callbacks.""" """Register callbacks."""

View File

@ -68,7 +68,7 @@ async def async_setup(hass, config):
pub_exclude.get(CONF_ENTITIES, []), pub_exclude.get(CONF_ENTITIES, []),
) )
if not base_topic.endswith("/"): if not base_topic.endswith("/"):
base_topic = base_topic + "/" base_topic = f"{base_topic}/"
@callback @callback
def _state_publisher(entity_id, old_state, new_state): def _state_publisher(entity_id, old_state, new_state):
@ -80,17 +80,17 @@ async def async_setup(hass, config):
payload = new_state.state payload = new_state.state
mybase = base_topic + entity_id.replace(".", "/") + "/" mybase = f"{base_topic}{entity_id.replace('.', '/')}/"
hass.components.mqtt.async_publish(mybase + "state", payload, 1, True) hass.components.mqtt.async_publish(f"{mybase}state", payload, 1, True)
if publish_timestamps: if publish_timestamps:
if new_state.last_updated: if new_state.last_updated:
hass.components.mqtt.async_publish( hass.components.mqtt.async_publish(
mybase + "last_updated", new_state.last_updated.isoformat(), 1, True f"{mybase}last_updated", new_state.last_updated.isoformat(), 1, True
) )
if new_state.last_changed: if new_state.last_changed:
hass.components.mqtt.async_publish( hass.components.mqtt.async_publish(
mybase + "last_changed", new_state.last_changed.isoformat(), 1, True f"{mybase}last_changed", new_state.last_changed.isoformat(), 1, True
) )
if publish_attributes: if publish_attributes:

View File

@ -199,9 +199,8 @@ class NeatoConnectedVacuum(StateVacuumDevice):
if robot_alert is None: if robot_alert is None:
self._clean_state = STATE_CLEANING self._clean_state = STATE_CLEANING
self._status_state = ( self._status_state = (
MODE.get(self._state["cleaning"]["mode"]) f"{MODE.get(self._state['cleaning']['mode'])} "
+ " " f"{ACTION.get(self._state['action'])}"
+ ACTION.get(self._state["action"])
) )
if ( if (
"boundary" in self._state["cleaning"] "boundary" in self._state["cleaning"]

View File

@ -32,7 +32,7 @@ ATTR_TOTAL_MATCHES = "total_matches"
CASCADE_URL = ( CASCADE_URL = (
"https://raw.githubusercontent.com/opencv/opencv/master/data/" "https://raw.githubusercontent.com/opencv/opencv/master/data/"
+ "lbpcascades/lbpcascade_frontalface.xml" "lbpcascades/lbpcascade_frontalface.xml"
) )
CONF_CLASSIFIER = "classifier" CONF_CLASSIFIER = "classifier"

View File

@ -225,7 +225,7 @@ class PioneerDevice(MediaPlayerDevice):
def set_volume_level(self, volume): def set_volume_level(self, volume):
"""Set volume level, range 0..1.""" """Set volume level, range 0..1."""
# 60dB max # 60dB max
self.telnet_command(str(round(volume * MAX_VOLUME)).zfill(3) + "VL") self.telnet_command(f"{round(volume * MAX_VOLUME):03}VL")
def mute_volume(self, mute): def mute_volume(self, mute):
"""Mute (true) or unmute (false) media player.""" """Mute (true) or unmute (false) media player."""
@ -237,4 +237,4 @@ class PioneerDevice(MediaPlayerDevice):
def select_source(self, source): def select_source(self, source):
"""Select input source.""" """Select input source."""
self.telnet_command(self._source_name_to_number.get(source) + "FN") self.telnet_command(f"{self._source_name_to_number.get(source)}FN")

View File

@ -160,7 +160,7 @@ class Proximity(Entity):
if (device_state.state).lower() == (self.friendly_name).lower(): if (device_state.state).lower() == (self.friendly_name).lower():
device_friendly = device_state.name device_friendly = device_state.name
if devices_in_zone != "": if devices_in_zone != "":
devices_in_zone = devices_in_zone + ", " devices_in_zone = f"{devices_in_zone}, "
devices_in_zone = devices_in_zone + device_friendly devices_in_zone = devices_in_zone + device_friendly
# No-one to track so reset the entity. # No-one to track so reset the entity.

View File

@ -54,7 +54,7 @@ RACHIO_API_EXCEPTIONS = (
STATUS_ONLINE = "ONLINE" STATUS_ONLINE = "ONLINE"
STATUS_OFFLINE = "OFFLINE" STATUS_OFFLINE = "OFFLINE"
SIGNAL_RACHIO_UPDATE = DOMAIN + "_update" SIGNAL_RACHIO_UPDATE = f"{DOMAIN}_update"
SIGNAL_RACHIO_CONTROLLER_UPDATE = SIGNAL_RACHIO_UPDATE + "_controller" SIGNAL_RACHIO_CONTROLLER_UPDATE = f"{SIGNAL_RACHIO_UPDATE}_controller"
SIGNAL_RACHIO_ZONE_UPDATE = SIGNAL_RACHIO_UPDATE + "_zone" SIGNAL_RACHIO_ZONE_UPDATE = f"{SIGNAL_RACHIO_UPDATE}_zone"
SIGNAL_RACHIO_SCHEDULE_UPDATE = SIGNAL_RACHIO_UPDATE + "_schedule" SIGNAL_RACHIO_SCHEDULE_UPDATE = f"{SIGNAL_RACHIO_UPDATE}_schedule"

View File

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

View File

@ -137,10 +137,12 @@ def _register_new_account(
request_id = configurator.async_request_config( request_id = configurator.async_request_config(
f"{DOMAIN} - {account_name}", f"{DOMAIN} - {account_name}",
callback=register_account_callback, callback=register_account_callback,
description="You need to log in to Remember The Milk to" description=(
+ "connect your account. \n\n" "You need to log in to Remember The Milk to"
+ 'Step 1: Click on the link "Remember The Milk login"\n\n' "connect your account. \n\n"
+ 'Step 2: Click on "login completed"', "Step 1: Click on the link 'Remember The Milk login'\n\n"
"Step 2: Click on 'login completed'"
),
link_name="Remember The Milk login", link_name="Remember The Milk login",
link_url=url, link_url=url,
submit_caption="login completed", submit_caption="login completed",

View File

@ -14,7 +14,7 @@ from homeassistant.helpers import config_validation as cv, discovery
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
DOMAIN = "waterfurnace" DOMAIN = "waterfurnace"
UPDATE_TOPIC = DOMAIN + "_update" UPDATE_TOPIC = f"{DOMAIN}_update"
SCAN_INTERVAL = timedelta(seconds=10) SCAN_INTERVAL = timedelta(seconds=10)
ERROR_INTERVAL = timedelta(seconds=300) ERROR_INTERVAL = timedelta(seconds=300)
MAX_FAILS = 10 MAX_FAILS = 10

View File

@ -39,6 +39,6 @@ SIGNAL_WEBSOCKET_CONNECTED = "websocket_connected"
SIGNAL_WEBSOCKET_DISCONNECTED = "websocket_disconnected" SIGNAL_WEBSOCKET_DISCONNECTED = "websocket_disconnected"
# Data used to store the current connection list # Data used to store the current connection list
DATA_CONNECTIONS = DOMAIN + ".connections" DATA_CONNECTIONS = f"{DOMAIN}.connections"
JSON_DUMP = partial(json.dumps, cls=JSONEncoder, allow_nan=False) JSON_DUMP = partial(json.dumps, cls=JSONEncoder, allow_nan=False)

View File

@ -104,8 +104,7 @@ class WinkWaterHeater(WinkDevice, WaterHeaterDevice):
else: else:
error = ( error = (
"Invalid operation mode mapping. " "Invalid operation mode mapping. "
+ mode f"{mode} doesn't map. Please report this."
+ " doesn't map. Please report this."
) )
_LOGGER.error(error) _LOGGER.error(error)
return op_list return op_list

View File

@ -134,8 +134,8 @@ def handle_homekit(hass, info) -> bool:
for test_model in HOMEKIT: for test_model in HOMEKIT:
if ( if (
model != test_model model != test_model
and not model.startswith(test_model + " ") and not model.startswith(f"{test_model} ")
and not model.startswith(test_model + "-") and not model.startswith(f"{test_model}-")
): ):
continue continue

View File

@ -774,9 +774,9 @@ async def async_binding_operation(zha_gateway, source_ieee, target_ieee, operati
res = await asyncio.gather(*(t[0] for t in bind_tasks), return_exceptions=True) res = await asyncio.gather(*(t[0] for t in bind_tasks), return_exceptions=True)
for outcome, log_msg in zip(res, bind_tasks): for outcome, log_msg in zip(res, bind_tasks):
if isinstance(outcome, Exception): if isinstance(outcome, Exception):
fmt = log_msg[1] + " failed: %s" fmt = f"{log_msg[1]} failed: %s"
else: else:
fmt = log_msg[1] + " completed: %s" fmt = f"{log_msg[1]} completed: %s"
zdo.debug(fmt, *(log_msg[2] + (outcome,))) zdo.debug(fmt, *(log_msg[2] + (outcome,)))

View File

@ -625,9 +625,9 @@ class ZHADevice(LogMixin):
res = await asyncio.gather(*(t[0] for t in tasks), return_exceptions=True) res = await asyncio.gather(*(t[0] for t in tasks), return_exceptions=True)
for outcome, log_msg in zip(res, tasks): for outcome, log_msg in zip(res, tasks):
if isinstance(outcome, Exception): if isinstance(outcome, Exception):
fmt = log_msg[1] + " failed: %s" fmt = f"{log_msg[1]} failed: %s"
else: else:
fmt = log_msg[1] + " completed: %s" fmt = f"{log_msg[1]} completed: %s"
zdo.debug(fmt, *(log_msg[2] + (outcome,))) zdo.debug(fmt, *(log_msg[2] + (outcome,)))
def log(self, level, msg, *args): def log(self, level, msg, *args):

View File

@ -102,7 +102,7 @@ def explore_module(package, explore_children):
if not hasattr(module, "__path__"): if not hasattr(module, "__path__"):
return found return found
for _, name, _ in pkgutil.iter_modules(module.__path__, package + "."): for _, name, _ in pkgutil.iter_modules(module.__path__, f"{package}."):
found.append(name) found.append(name)
if explore_children: if explore_children:
@ -169,10 +169,7 @@ def gather_requirements_from_manifests(errors, reqs):
continue continue
process_requirements( process_requirements(
errors, errors, integration.requirements, f"homeassistant.components.{domain}", reqs
integration.requirements,
f"homeassistant.components.{domain}",
reqs,
) )

View File

@ -13,7 +13,7 @@ def explore_module(package):
module = importlib.import_module(package) module = importlib.import_module(package)
if not hasattr(module, "__path__"): if not hasattr(module, "__path__"):
return [] return []
for _, name, _ in pkgutil.iter_modules(module.__path__, package + "."): for _, name, _ in pkgutil.iter_modules(module.__path__, f"{package}."):
yield name yield name