Skip to content

Commit

Permalink
Improve string formatting v4 (home-assistant#33668)
Browse files Browse the repository at this point in the history
* Improve string formatting v4

* Use normal strings instead of f-strings

* Fix zeroconf test by adding back part of a condition
  • Loading branch information
springstan authored Apr 5, 2020
1 parent b855177 commit e3bcfb8
Show file tree
Hide file tree
Showing 20 changed files with 43 additions and 47 deletions.
6 changes: 2 additions & 4 deletions homeassistant/components/almond/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,10 +291,8 @@ async def async_process(
buffer += f"\n Picture: {message['url']}"
elif message["type"] == "rdl":
buffer += (
"\n Link: "
+ message["rdl"]["displayTitle"]
+ " "
+ message["rdl"]["webCallback"]
f"\n Link: {message['rdl']['displayTitle']} "
f"{message['rdl']['webCallback']}"
)
elif message["type"] == "choice":
if first_choice:
Expand Down
5 changes: 2 additions & 3 deletions homeassistant/components/anthemav/media_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,9 +142,8 @@ def media_title(self):
def app_name(self):
"""Return details about current video and audio stream."""
return (
self._lookup("video_input_resolution_text", "")
+ " "
+ self._lookup("audio_input_name", "")
f"{self._lookup('video_input_resolution_text', '')} "
f"{self._lookup('audio_input_name', '')}"
)

@property
Expand Down
6 changes: 4 additions & 2 deletions homeassistant/components/braviatv/media_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,8 +154,10 @@ def bravia_configuration_callback(data):
_CONFIGURING[host] = configurator.request_config(
name,
bravia_configuration_callback,
description="Enter the Pin shown on your Sony Bravia TV."
+ "If no Pin is shown, enter 0000 to let TV show you a Pin.",
description=(
"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",
submit_caption="Confirm",
fields=[{"id": "pin", "name": "Enter the pin", "type": ""}],
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/envisalink/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def __init__(self, hass, partition_name, partition_number, info, controller):
self._partition_number = partition_number

_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):
"""Register callbacks."""
Expand Down
10 changes: 5 additions & 5 deletions homeassistant/components/mqtt_statestream/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ async def async_setup(hass, config):
pub_exclude.get(CONF_ENTITIES, []),
)
if not base_topic.endswith("/"):
base_topic = base_topic + "/"
base_topic = f"{base_topic}/"

@callback
def _state_publisher(entity_id, old_state, new_state):
Expand All @@ -80,17 +80,17 @@ def _state_publisher(entity_id, old_state, new_state):

payload = new_state.state

mybase = base_topic + entity_id.replace(".", "/") + "/"
hass.components.mqtt.async_publish(mybase + "state", payload, 1, True)
mybase = f"{base_topic}{entity_id.replace('.', '/')}/"
hass.components.mqtt.async_publish(f"{mybase}state", payload, 1, True)

if publish_timestamps:
if new_state.last_updated:
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:
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:
Expand Down
5 changes: 2 additions & 3 deletions homeassistant/components/neato/vacuum.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,9 +199,8 @@ def update(self):
if robot_alert is None:
self._clean_state = STATE_CLEANING
self._status_state = (
MODE.get(self._state["cleaning"]["mode"])
+ " "
+ ACTION.get(self._state["action"])
f"{MODE.get(self._state['cleaning']['mode'])} "
f"{ACTION.get(self._state['action'])}"
)
if (
"boundary" in self._state["cleaning"]
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/opencv/image_processing.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@

CASCADE_URL = (
"https://raw.githubusercontent.com/opencv/opencv/master/data/"
+ "lbpcascades/lbpcascade_frontalface.xml"
"lbpcascades/lbpcascade_frontalface.xml"
)

CONF_CLASSIFIER = "classifier"
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/pioneer/media_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ def volume_down(self):
def set_volume_level(self, volume):
"""Set volume level, range 0..1."""
# 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):
"""Mute (true) or unmute (false) media player."""
Expand All @@ -237,4 +237,4 @@ def turn_on(self):

def select_source(self, 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")
2 changes: 1 addition & 1 deletion homeassistant/components/proximity/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ def check_proximity_state_change(self, entity, old_state, new_state):
if (device_state.state).lower() == (self.friendly_name).lower():
device_friendly = device_state.name
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

# No-one to track so reset the entity.
Expand Down
8 changes: 4 additions & 4 deletions homeassistant/components/rachio/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
STATUS_ONLINE = "ONLINE"
STATUS_OFFLINE = "OFFLINE"

SIGNAL_RACHIO_UPDATE = DOMAIN + "_update"
SIGNAL_RACHIO_CONTROLLER_UPDATE = SIGNAL_RACHIO_UPDATE + "_controller"
SIGNAL_RACHIO_ZONE_UPDATE = SIGNAL_RACHIO_UPDATE + "_zone"
SIGNAL_RACHIO_SCHEDULE_UPDATE = SIGNAL_RACHIO_UPDATE + "_schedule"
SIGNAL_RACHIO_UPDATE = f"{DOMAIN}_update"
SIGNAL_RACHIO_CONTROLLER_UPDATE = f"{SIGNAL_RACHIO_UPDATE}_controller"
SIGNAL_RACHIO_ZONE_UPDATE = f"{SIGNAL_RACHIO_UPDATE}_zone"
SIGNAL_RACHIO_SCHEDULE_UPDATE = f"{SIGNAL_RACHIO_UPDATE}_schedule"
2 changes: 1 addition & 1 deletion homeassistant/components/raspihats/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def online_callback():

def _log_message(self, message):
"""Create log message."""
string = self._name + " "
string = f"{self._name} "
string += f"{self._board}I2CHat@{hex(self._address)} "
string += f"channel:{str(self._channel)}{message}"
return string
Expand Down
10 changes: 6 additions & 4 deletions homeassistant/components/remember_the_milk/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,10 +137,12 @@ def register_account_callback(_):
request_id = configurator.async_request_config(
f"{DOMAIN} - {account_name}",
callback=register_account_callback,
description="You need to log in to Remember The Milk to"
+ "connect your account. \n\n"
+ 'Step 1: Click on the link "Remember The Milk login"\n\n'
+ 'Step 2: Click on "login completed"',
description=(
"You need to log in to Remember The Milk to"
"connect your account. \n\n"
"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_url=url,
submit_caption="login completed",
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/waterfurnace/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
_LOGGER = logging.getLogger(__name__)

DOMAIN = "waterfurnace"
UPDATE_TOPIC = DOMAIN + "_update"
UPDATE_TOPIC = f"{DOMAIN}_update"
SCAN_INTERVAL = timedelta(seconds=10)
ERROR_INTERVAL = timedelta(seconds=300)
MAX_FAILS = 10
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/websocket_api/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,6 @@
SIGNAL_WEBSOCKET_DISCONNECTED = "websocket_disconnected"

# 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)
3 changes: 1 addition & 2 deletions homeassistant/components/wink/water_heater.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,7 @@ def operation_list(self):
else:
error = (
"Invalid operation mode mapping. "
+ mode
+ " doesn't map. Please report this."
f"{mode} doesn't map. Please report this."
)
_LOGGER.error(error)
return op_list
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/zeroconf/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,8 @@ def handle_homekit(hass, info) -> bool:
for test_model in HOMEKIT:
if (
model != test_model
and not model.startswith(test_model + " ")
and not model.startswith(test_model + "-")
and not model.startswith(f"{test_model} ")
and not model.startswith(f"{test_model}-")
):
continue

Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/zha/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
for outcome, log_msg in zip(res, bind_tasks):
if isinstance(outcome, Exception):
fmt = log_msg[1] + " failed: %s"
fmt = f"{log_msg[1]} failed: %s"
else:
fmt = log_msg[1] + " completed: %s"
fmt = f"{log_msg[1]} completed: %s"
zdo.debug(fmt, *(log_msg[2] + (outcome,)))


Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/zha/core/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -625,9 +625,9 @@ async def _async_group_binding_operation(
res = await asyncio.gather(*(t[0] for t in tasks), return_exceptions=True)
for outcome, log_msg in zip(res, tasks):
if isinstance(outcome, Exception):
fmt = log_msg[1] + " failed: %s"
fmt = f"{log_msg[1]} failed: %s"
else:
fmt = log_msg[1] + " completed: %s"
fmt = f"{log_msg[1]} completed: %s"
zdo.debug(fmt, *(log_msg[2] + (outcome,)))

def log(self, level, msg, *args):
Expand Down
7 changes: 2 additions & 5 deletions script/gen_requirements_all.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ def explore_module(package, explore_children):
if not hasattr(module, "__path__"):
return found

for _, name, _ in pkgutil.iter_modules(module.__path__, package + "."):
for _, name, _ in pkgutil.iter_modules(module.__path__, f"{package}."):
found.append(name)

if explore_children:
Expand Down Expand Up @@ -169,10 +169,7 @@ def gather_requirements_from_manifests(errors, reqs):
continue

process_requirements(
errors,
integration.requirements,
f"homeassistant.components.{domain}",
reqs,
errors, integration.requirements, f"homeassistant.components.{domain}", reqs
)


Expand Down
2 changes: 1 addition & 1 deletion script/inspect_schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ def explore_module(package):
module = importlib.import_module(package)
if not hasattr(module, "__path__"):
return []
for _, name, _ in pkgutil.iter_modules(module.__path__, package + "."):
for _, name, _ in pkgutil.iter_modules(module.__path__, f"{package}."):
yield name


Expand Down

0 comments on commit e3bcfb8

Please sign in to comment.