Skip to content

Commit

Permalink
String formatting cleanups (home-assistant#52937)
Browse files Browse the repository at this point in the history
  • Loading branch information
scop authored Jul 12, 2021
1 parent 2970931 commit 9864f2e
Show file tree
Hide file tree
Showing 22 changed files with 32 additions and 35 deletions.
2 changes: 1 addition & 1 deletion homeassistant/components/buienradar/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ async def get_data(self, url):

return result
except (asyncio.TimeoutError, aiohttp.ClientError) as err:
result[MESSAGE] = "%s" % err
result[MESSAGE] = str(err)
return result
finally:
if resp is not None:
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/cisco_ios/device_tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ def _get_arp_data(self):
router_hostname = initial_line[len(initial_line) - 1]
router_hostname += "#"
# Set the discovered hostname as prompt
regex_expression = ("(?i)^%s" % router_hostname).encode()
regex_expression = f"(?i)^{router_hostname}".encode()
cisco_ssh.PROMPT = re.compile(regex_expression, re.MULTILINE)
# Allow full arp table to print at once
cisco_ssh.sendline("terminal length 0")
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/etherscan/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
if token:
token = token.upper()
if not name:
name = "%s Balance" % token
name = f"{token} Balance"
if not name:
name = "ETH Balance"

Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/google_travel_time/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def get_location_from_entity(hass, logger, entity_id):
return get_location_from_attributes(entity)

# Check if device is in a zone
zone_entity = hass.states.get("zone.%s" % entity.state)
zone_entity = hass.states.get(f"zone.{entity.state}")
if location.has_location(zone_entity):
logger.debug(
"%s is in %s, getting zone location", entity_id, zone_entity.entity_id
Expand Down
3 changes: 1 addition & 2 deletions homeassistant/components/mailbox/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,8 +254,7 @@ async def get(self, request, platform, msgid):
try:
stream = await mailbox.async_get_media(msgid)
except StreamError as err:
error_msg = "Error getting media: %s" % (err)
_LOGGER.error(error_msg)
_LOGGER.error("Error getting media: %s", err)
return web.Response(status=HTTP_INTERNAL_SERVER_ERROR)
if stream:
return web.Response(body=stream, content_type=mailbox.media_type)
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/mobile_app/webhook.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ async def webhook_stream_camera(hass, config_entry, data):
status=HTTP_BAD_REQUEST,
)

resp = {"mjpeg_path": "/api/camera_proxy_stream/%s" % (camera.entity_id)}
resp = {"mjpeg_path": f"/api/camera_proxy_stream/{camera.entity_id}"}

if camera.attributes[ATTR_SUPPORTED_FEATURES] & CAMERA_SUPPORT_STREAM:
try:
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/mochad/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def __init__(self, hass, ctrl, dev):

self._controller = ctrl
self._address = dev[CONF_ADDRESS]
self._name = dev.get(CONF_NAME, "x10_switch_dev_%s" % self._address)
self._name = dev.get(CONF_NAME, f"x10_switch_dev_{self._address}")
self._comm_type = dev.get(CONF_COMM_TYPE, "pl")
self.switch = device.Device(ctrl, self._address, comm_type=self._comm_type)
# Init with false to avoid locking HA for long on CM19A (goes from rf
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/nest/legacy/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,9 @@ async def async_setup_legacy_entry(hass, entry, async_add_entities):
if variable in _SENSOR_TYPES_DEPRECATED:
if variable in DEPRECATED_WEATHER_VARS:
wstr = (
"Nest no longer provides weather data like %s. See "
f"Nest no longer provides weather data like {variable}. See "
"https://www.home-assistant.io/integrations/#weather "
"for a list of other weather integrations to use." % variable
"for a list of other weather integrations to use."
)
else:
wstr = (
Expand Down
8 changes: 4 additions & 4 deletions homeassistant/components/netio/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,12 @@ def get(self, request, host):

for i in range(1, 5):
out = "output%d" % i
states.append(data.get("%s_state" % out) == STATE_ON)
consumptions.append(float(data.get("%s_consumption" % out, 0)))
states.append(data.get(f"{out}_state") == STATE_ON)
consumptions.append(float(data.get(f"{out}_consumption", 0)))
cumulated_consumptions.append(
float(data.get("%s_cumulatedConsumption" % out, 0)) / 1000
float(data.get(f"{out}_cumulatedConsumption", 0)) / 1000
)
start_dates.append(data.get("%s_consumptionStart" % out, ""))
start_dates.append(data.get(f"{out}_consumptionStart", ""))

_LOGGER.debug(
"%s: %s, %s, %s since %s",
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/octoprint/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ def get(self, endpoint):
return response.json()

except requests.ConnectionError as exc_con:
log_string = "Failed to connect to Octoprint server. Error: %s" % exc_con
log_string = f"Failed to connect to Octoprint server. Error: {exc_con}"

if not self.available_error_logged:
_LOGGER.error(log_string)
Expand All @@ -254,7 +254,7 @@ def get(self, endpoint):
except requests.HTTPError as ex_http:
status_code = ex_http.response.status_code

log_string = "Failed to update OctoPrint status. Error: %s" % ex_http
log_string = f"Failed to update OctoPrint status. Error: {ex_http}"
# Only log the first failure
if endpoint == "job":
log_string = f"Endpoint: job {log_string}"
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/openhardwaremonitor/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ def update(self):
self.attributes = _attributes
return
array = array[path_number][OHM_CHILDREN]
_attributes.update({"level_%s" % path_index: values[OHM_NAME]})
_attributes.update({f"level_{path_index}": values[OHM_NAME]})


class OpenHardwareMonitorData:
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/rss_feed_template/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
def setup(hass, config):
"""Set up the RSS feed template component."""
for (feeduri, feedconfig) in config[DOMAIN].items():
url = "/api/rss_template/%s" % feeduri
url = f"/api/rss_template/{feeduri}"

requires_auth = feedconfig.get("requires_api_password")

Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/smtp/notify.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ def _attach_file(atch_name, content_id):
atch_name,
)
attachment = MIMEApplication(file_bytes, Name=atch_name)
attachment["Content-Disposition"] = "attachment; " 'filename="%s"' % atch_name
attachment["Content-Disposition"] = f'attachment; filename="{atch_name}"'

attachment.add_header("Content-ID", f"<{content_id}>")
return attachment
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/statsd/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def statsd_event_listener(event):

if show_attribute_flag is True:
if isinstance(_state, (float, int)):
statsd_client.gauge("%s.state" % state.entity_id, _state, sample_rate)
statsd_client.gauge(f"{state.entity_id}.state", _state, sample_rate)

# Send attribute values
for key, value in states.items():
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/xiaomi_aqara/light.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def parse_data(self, data, raw_data):
self._state = False
return True

rgbhexstr = "%x" % value
rgbhexstr = f"{value:x}"
if len(rgbhexstr) > 8:
_LOGGER.error(
"Light RGB data error."
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/util/async_.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def fire_coroutine_threadsafe(coro: Coroutine, loop: AbstractEventLoop) -> None:
raise RuntimeError("Cannot be called from within the event loop")

if not coroutines.iscoroutine(coro):
raise TypeError("A coroutine object is required: %s" % coro)
raise TypeError(f"A coroutine object is required: {coro}")

def callback() -> None:
"""Handle the firing of a coroutine."""
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/util/ruamel_yaml.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def _include_yaml(
"""
if constructor.name is None:
raise HomeAssistantError(
"YAML include error: filename not set for %s" % node.value
f"YAML include error: filename not set for {node.value}"
)
fname = os.path.join(os.path.dirname(constructor.name), node.value)
return load_yaml(fname, False)
Expand Down
2 changes: 1 addition & 1 deletion tests/auth/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,7 @@ async def test_saving_loading(hass, hass_storage):
assert r_token.last_used_at is None
assert r_token.last_used_ip is None
else:
assert False, "Unknown client_id: %s" % r_token.client_id
assert False, f"Unknown client_id: {r_token.client_id}"


async def test_cannot_retrieve_expired_access_token(hass):
Expand Down
2 changes: 1 addition & 1 deletion tests/components/foobot/test_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ async def test_default_setup(hass, aioclient_mock):
}

for name, value in metrics.items():
state = hass.states.get("sensor.foobot_happybot_%s" % name)
state = hass.states.get(f"sensor.foobot_happybot_{name}")
assert state.state == value[0]
assert state.attributes.get("unit_of_measurement") == value[1]

Expand Down
2 changes: 1 addition & 1 deletion tests/components/hyperion/test_light.py
Original file line number Diff line number Diff line change
Expand Up @@ -1384,7 +1384,7 @@ async def test_deprecated_effect_names(caplog, hass: HomeAssistant) -> None:
{ATTR_ENTITY_ID: TEST_ENTITY_ID_1, ATTR_EFFECT: component},
blocking=True,
)
assert "Use of Hyperion effect '%s' is deprecated" % component in caplog.text
assert f"Use of Hyperion effect '{component}' is deprecated" in caplog.text

# Simulate a state callback from Hyperion.
client.visible_priority = {
Expand Down
10 changes: 5 additions & 5 deletions tests/components/mailbox/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ async def test_get_media_from_mailbox(mock_http_client):
msgtxt = "Message 1. Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
msgsha = sha1(msgtxt.encode("utf-8")).hexdigest()

url = "/api/mailbox/media/DemoMailbox/%s" % (msgsha)
url = f"/api/mailbox/media/DemoMailbox/{msgsha}"
req = await mock_http_client.get(url)
assert req.status == 200
data = await req.read()
Expand All @@ -58,7 +58,7 @@ async def test_delete_from_mailbox(mock_http_client):
msgsha2 = sha1(msgtxt2.encode("utf-8")).hexdigest()

for msg in [msgsha1, msgsha2]:
url = "/api/mailbox/delete/DemoMailbox/%s" % (msg)
url = f"/api/mailbox/delete/DemoMailbox/{msg}"
req = await mock_http_client.delete(url)
assert req.status == 200

Expand All @@ -80,7 +80,7 @@ async def test_get_messages_from_invalid_mailbox(mock_http_client):
async def test_get_media_from_invalid_mailbox(mock_http_client):
"""Get messages from mailbox."""
msgsha = "0000000000000000000000000000000000000000"
url = "/api/mailbox/media/mailbox.invalid_mailbox/%s" % (msgsha)
url = f"/api/mailbox/media/mailbox.invalid_mailbox/{msgsha}"

req = await mock_http_client.get(url)
assert req.status == HTTP_NOT_FOUND
Expand All @@ -89,7 +89,7 @@ async def test_get_media_from_invalid_mailbox(mock_http_client):
async def test_get_media_from_invalid_msgid(mock_http_client):
"""Get messages from mailbox."""
msgsha = "0000000000000000000000000000000000000000"
url = "/api/mailbox/media/DemoMailbox/%s" % (msgsha)
url = f"/api/mailbox/media/DemoMailbox/{msgsha}"

req = await mock_http_client.get(url)
assert req.status == HTTP_INTERNAL_SERVER_ERROR
Expand All @@ -98,7 +98,7 @@ async def test_get_media_from_invalid_msgid(mock_http_client):
async def test_delete_from_invalid_mailbox(mock_http_client):
"""Get audio from mailbox."""
msgsha = "0000000000000000000000000000000000000000"
url = "/api/mailbox/delete/mailbox.invalid_mailbox/%s" % (msgsha)
url = f"/api/mailbox/delete/mailbox.invalid_mailbox/{msgsha}"

req = await mock_http_client.delete(url)
assert req.status == HTTP_NOT_FOUND
6 changes: 2 additions & 4 deletions tests/components/statsd/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,10 +110,8 @@ async def test_event_listener_attr_details(hass, mock_client):
handler_method(MagicMock(data={"new_state": state}))
mock_client.gauge.assert_has_calls(
[
mock.call("%s.state" % state.entity_id, out, statsd.DEFAULT_RATE),
mock.call(
"%s.attribute_key" % state.entity_id, 3.2, statsd.DEFAULT_RATE
),
mock.call(f"{state.entity_id}.state", out, statsd.DEFAULT_RATE),
mock.call(f"{state.entity_id}.attribute_key", 3.2, statsd.DEFAULT_RATE),
]
)

Expand Down

0 comments on commit 9864f2e

Please sign in to comment.