Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update string formatting to use f-string on components #125987

Merged
merged 4 commits into from
Sep 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion homeassistant/components/buienradar/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -888,7 +888,7 @@
if sensor_type.startswith(PRECIPITATION_FORECAST):
result = {ATTR_ATTRIBUTION: data.get(ATTRIBUTION)}
if self._timeframe is not None:
result[TIMEFRAME_LABEL] = "%d min" % (self._timeframe)
result[TIMEFRAME_LABEL] = f"{self._timeframe} min"

Check warning on line 891 in homeassistant/components/buienradar/sensor.py

View check run for this annotation

Codecov / codecov/patch

homeassistant/components/buienradar/sensor.py#L891

Added line #L891 was not covered by tests

self._attr_extra_state_attributes = result

Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/buienradar/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ async def get_data(self, url):
if resp.status == HTTPStatus.OK:
result[SUCCESS] = True
else:
result[MESSAGE] = "Got http statuscode: %d" % (resp.status)
result[MESSAGE] = f"Got http statuscode: {resp.status}"

return result
except (TimeoutError, aiohttp.ClientError) as err:
Expand Down
6 changes: 2 additions & 4 deletions homeassistant/components/emoncms_history/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,15 +86,13 @@
continue

if payload_dict:
payload = "{{{}}}".format(
",".join(f"{key}:{val}" for key, val in payload_dict.items())
)
payload = ",".join(f"{key}:{val}" for key, val in payload_dict.items())

Check warning on line 89 in homeassistant/components/emoncms_history/__init__.py

View check run for this annotation

Codecov / codecov/patch

homeassistant/components/emoncms_history/__init__.py#L89

Added line #L89 was not covered by tests

send_data(
conf.get(CONF_URL),
conf.get(CONF_API_KEY),
str(conf.get(CONF_INPUTNODE)),
payload,
f"{{{payload}}}",
)

track_point_in_time(
Expand Down
3 changes: 1 addition & 2 deletions homeassistant/components/graphite/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,8 +138,7 @@ def _report_attributes(self, entity_id, new_state):
with suppress(ValueError):
things["state"] = state.state_as_number(new_state)
lines = [
"%s.%s.%s %f %i"
% (self._prefix, entity_id, key.replace(" ", "_"), value, now)
f"{self._prefix}.{entity_id}.{key.replace(' ', '_')} {value:f} {now}"
for key, value in things.items()
if isinstance(value, (float, int))
]
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/home_connect/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ def get_program_sensors(self):
ATTR_DEVICE: self,
ATTR_DESC: k,
ATTR_UNIT: unit,
ATTR_KEY: "BSH.Common.Option.{}".format(k.replace(" ", "")),
ATTR_KEY: f"BSH.Common.Option.{k.replace(' ', '')}",
ATTR_ICON: icon,
ATTR_DEVICE_CLASS: device_class,
ATTR_SIGN: sign,
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/kira/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def load_module(platform, idx, module_conf):
"""Set up the KIRA module and load platform."""
# note: module_name is not the HA device name. it's just a unique name
# to ensure the component and platform can share information
module_name = ("%s_%d" % (DOMAIN, idx)) if idx else DOMAIN
module_name = f"{DOMAIN}_{idx}" if idx else DOMAIN
device_name = module_conf.get(CONF_NAME, DOMAIN)
port = module_conf.get(CONF_PORT, DEFAULT_PORT)
host = module_conf.get(CONF_HOST, DEFAULT_HOST)
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/limitlessled/light.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,13 +119,13 @@
else:
_LOGGER.warning("Legacy configuration format detected")
for i in range(1, 5):
name_key = "group_%d_name" % i
name_key = f"group_{i}_name"

Check warning on line 122 in homeassistant/components/limitlessled/light.py

View check run for this annotation

Codecov / codecov/patch

homeassistant/components/limitlessled/light.py#L122

Added line #L122 was not covered by tests
if name_key in bridge_conf:
groups.append(
{
"number": i,
"type": bridge_conf.get(
"group_%d_type" % i, DEFAULT_LED_TYPE
f"group_{i}_type", DEFAULT_LED_TYPE
),
"name": bridge_conf.get(name_key),
}
Expand Down
6 changes: 4 additions & 2 deletions homeassistant/components/mysensors/light.py
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,8 @@ def _turn_on_rgb(self, **kwargs: Any) -> None:
new_rgb: tuple[int, int, int] | None = kwargs.get(ATTR_RGB_COLOR)
if new_rgb is None:
return
hex_color = "{:02x}{:02x}{:02x}".format(*new_rgb)
red, green, blue = new_rgb
hex_color = f"{red:02x}{green:02x}{blue:02x}"
self.gateway.set_child_value(
self.node_id, self.child_id, self.value_type, hex_color, ack=1
)
Expand Down Expand Up @@ -220,7 +221,8 @@ def _turn_on_rgbw(self, **kwargs: Any) -> None:
new_rgbw: tuple[int, int, int, int] | None = kwargs.get(ATTR_RGBW_COLOR)
if new_rgbw is None:
return
hex_color = "{:02x}{:02x}{:02x}{:02x}".format(*new_rgbw)
red, green, blue, white = new_rgbw
hex_color = f"{red:02x}{green:02x}{blue:02x}{white:02x}"
self.gateway.set_child_value(
self.node_id, self.child_id, self.value_type, hex_color, ack=1
)
Expand Down
5 changes: 3 additions & 2 deletions homeassistant/components/netio/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@
states, consumptions, cumulated_consumptions, start_dates = [], [], [], []

for i in range(1, 5):
out = "output%d" % i
out = f"output{i}"

Check warning on line 112 in homeassistant/components/netio/switch.py

View check run for this annotation

Codecov / codecov/patch

homeassistant/components/netio/switch.py#L112

Added line #L112 was not covered by tests
states.append(data.get(f"{out}_state") == STATE_ON)
consumptions.append(float(data.get(f"{out}_consumption", 0)))
cumulated_consumptions.append(
Expand Down Expand Up @@ -168,7 +168,8 @@
def _set(self, value):
val = list("uuuu")
val[int(self.outlet) - 1] = "1" if value else "0"
self.netio.get("port list {}".format("".join(val)))
val = "".join(val)
self.netio.get(f"port list {val}")

Check warning on line 172 in homeassistant/components/netio/switch.py

View check run for this annotation

Codecov / codecov/patch

homeassistant/components/netio/switch.py#L171-L172

Added lines #L171 - L172 were not covered by tests
self.netio.states[int(self.outlet) - 1] = value
self.schedule_update_ha_state()

Expand Down
13 changes: 6 additions & 7 deletions homeassistant/components/numato/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -185,14 +185,13 @@
if (device_id, port) not in self.ports_registered:
self.ports_registered[(device_id, port)] = direction
else:
io = (

Check warning on line 188 in homeassistant/components/numato/__init__.py

View check run for this annotation

Codecov / codecov/patch

homeassistant/components/numato/__init__.py#L188

Added line #L188 was not covered by tests
"input"
if self.ports_registered[(device_id, port)] == gpio.IN
else "output"
)
raise gpio.NumatoGpioError(
"Device {} port {} already in use as {}.".format(
device_id,
port,
"input"
if self.ports_registered[(device_id, port)] == gpio.IN
else "output",
)
f"Device {device_id} port {port} already in use as {io}."
)

def check_device_id(self, device_id: int) -> None:
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/recorder/executor.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def weakref_cb( # type: ignore[no-untyped-def]

num_threads = len(self._threads)
if num_threads < self._max_workers:
thread_name = "%s_%d" % (self._thread_name_prefix or self, num_threads)
thread_name = f"{self._thread_name_prefix or self}_{num_threads}"
executor_thread = threading.Thread(
name=thread_name,
target=_worker_with_shutdown_hook,
Expand Down
26 changes: 9 additions & 17 deletions homeassistant/components/recorder/migration.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,9 +288,11 @@ def _migrate_schema(
"The database is about to upgrade from schema version %s to %s%s",
current_version,
end_version,
f". {MIGRATION_NOTE_OFFLINE}"
if current_version < LIVE_MIGRATION_MIN_SCHEMA_VERSION
else "",
(
f". {MIGRATION_NOTE_OFFLINE}"
if current_version < LIVE_MIGRATION_MIN_SCHEMA_VERSION
else ""
),
)
schema_status = dataclass_replace(schema_status, current_version=end_version)

Expand Down Expand Up @@ -475,11 +477,7 @@ def _add_columns(
try:
connection = session.connection()
connection.execute(
text(
"ALTER TABLE {table} {columns_def}".format(
table=table_name, columns_def=", ".join(columns_def)
)
)
text(f"ALTER TABLE {table_name} {', '.join(columns_def)}")
)
except (InternalError, OperationalError, ProgrammingError):
# Some engines support adding all columns at once,
Expand Down Expand Up @@ -530,10 +528,8 @@ def _modify_columns(

if engine.dialect.name == SupportedDialect.POSTGRESQL:
columns_def = [
"ALTER {column} TYPE {type}".format(
**dict(zip(["column", "type"], col_def.split(" ", 1), strict=False))
)
for col_def in columns_def
f"ALTER {column} TYPE {type_}"
for column, type_ in (col_def.split(" ", 1) for col_def in columns_def)
]
elif engine.dialect.name == "mssql":
columns_def = [f"ALTER COLUMN {col_def}" for col_def in columns_def]
Expand All @@ -544,11 +540,7 @@ def _modify_columns(
try:
connection = session.connection()
connection.execute(
text(
"ALTER TABLE {table} {columns_def}".format(
table=table_name, columns_def=", ".join(columns_def)
)
)
text(f"ALTER TABLE {table_name} {', '.join(columns_def)}")
)
except (InternalError, OperationalError):
_LOGGER.info("Unable to use quick column modify. Modifying 1 by 1")
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/sense/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@

def sense_to_mdi(sense_icon):
"""Convert sense icon to mdi icon."""
return "mdi:{}".format(MDI_ICONS.get(sense_icon, "power-plug"))
return f"mdi:{MDI_ICONS.get(sense_icon, "power-plug")}"

Check warning on line 59 in homeassistant/components/sense/binary_sensor.py

View check run for this annotation

Codecov / codecov/patch

homeassistant/components/sense/binary_sensor.py#L59

Added line #L59 was not covered by tests


class SenseDevice(BinarySensorEntity):
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/sense/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@

def sense_to_mdi(sense_icon):
"""Convert sense icon to mdi icon."""
return "mdi:{}".format(MDI_ICONS.get(sense_icon, "power-plug"))
return f"mdi:{MDI_ICONS.get(sense_icon, 'power-plug')}"

Check warning on line 81 in homeassistant/components/sense/sensor.py

View check run for this annotation

Codecov / codecov/patch

homeassistant/components/sense/sensor.py#L81

Added line #L81 was not covered by tests


async def async_setup_entry(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def __init__(self, hass, camera_entity, config, name):

self.filepath = os.path.join(
self.hass.config.config_dir,
"ssocr-{}.png".format(self._name.replace(" ", "_")),
f"ssocr-{self._name.replace(' ', '_')}.png",
)
crop = [
"crop",
Expand Down
6 changes: 2 additions & 4 deletions homeassistant/components/shopping_list/intent.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,10 +53,8 @@ async def async_handle(self, intent_obj: intent.Intent) -> intent.IntentResponse
if not items:
response.async_set_speech("There are no items on your shopping list")
else:
items_list = ", ".join(itm["name"] for itm in reversed(items))
response.async_set_speech(
"These are the top {} items on your shopping list: {}".format(
min(len(items), 5),
", ".join(itm["name"] for itm in reversed(items)),
)
f"These are the top {min(len(items), 5)} items on your shopping list: {items_list}"
)
return response
9 changes: 4 additions & 5 deletions homeassistant/components/signal_messenger/notify.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,12 +166,11 @@ def get_attachments_as_bytes(
and int(str(resp.headers.get("Content-Length")))
> attachment_size_limit
):
content_length = int(str(resp.headers.get("Content-Length")))
raise ValueError( # noqa: TRY301
"Attachment too large (Content-Length reports {}). Max size: {}"
" bytes".format(
int(str(resp.headers.get("Content-Length"))),
CONF_MAX_ALLOWED_DOWNLOAD_SIZE_BYTES,
)
"Attachment too large (Content-Length reports "
f"{content_length}). Max size: "
f"{CONF_MAX_ALLOWED_DOWNLOAD_SIZE_BYTES} bytes"
)

size = 0
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/skybeacon/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@
value[2],
value[1],
)
self.data["temp"] = float("%d.%d" % (value[0], value[2]))
self.data["temp"] = float(f"{value[0]}.{value[2]}")

Check warning on line 187 in homeassistant/components/skybeacon/sensor.py

View check run for this annotation

Codecov / codecov/patch

homeassistant/components/skybeacon/sensor.py#L187

Added line #L187 was not covered by tests
self.data["humid"] = value[1]

def terminate(self):
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/snips/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ async def message_received(msg):
slots = {}
for slot in request.get("slots", []):
slots[slot["slotName"]] = {"value": resolve_slot_values(slot)}
slots["{}_raw".format(slot["slotName"])] = {"value": slot["rawValue"]}
slots[f"{slot['slotName']}_raw"] = {"value": slot["rawValue"]}
slots["site_id"] = {"value": request.get("siteId")}
slots["session_id"] = {"value": request.get("sessionId")}
slots["confidenceScore"] = {"value": request["intent"]["confidenceScore"]}
Expand Down
5 changes: 2 additions & 3 deletions homeassistant/components/starlingbank/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,8 @@
@property
def name(self):
"""Return the name of the sensor."""
return "{} {}".format(
self._account_name, self._balance_data_type.replace("_", " ").capitalize()
)
balance_data_type = self._balance_data_type.replace("_", " ").capitalize()
return f"{self._account_name} {balance_data_type}"

Check warning on line 96 in homeassistant/components/starlingbank/sensor.py

View check run for this annotation

Codecov / codecov/patch

homeassistant/components/starlingbank/sensor.py#L95-L96

Added lines #L95 - L96 were not covered by tests

@property
def native_value(self):
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 @@ -80,7 +80,7 @@ def statsd_event_listener(event):
# Send attribute values
for key, value in states.items():
if isinstance(value, (float, int)):
stat = "{}.{}".format(state.entity_id, key.replace(" ", "_"))
stat = f"{state.entity_id}.{key.replace(' ', '_')}"
statsd_client.gauge(stat, value, sample_rate)

elif isinstance(_state, (float, int)):
Expand Down
12 changes: 7 additions & 5 deletions homeassistant/components/stream/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -367,12 +367,14 @@ def flush(self, packet: av.Packet, last_part: bool) -> None:
data=self._memory_file.read(),
),
(
segment_duration := float(
(adjusted_dts - self._segment_start_dts) * packet.time_base
(
segment_duration := float(
(adjusted_dts - self._segment_start_dts) * packet.time_base
)
)
)
if last_part
else 0,
if last_part
albertomontesg marked this conversation as resolved.
Show resolved Hide resolved
else 0
),
)
if last_part:
# If we've written the last part, we can close the memory_file.
Expand Down
7 changes: 3 additions & 4 deletions homeassistant/components/supla/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,9 @@
@property
def unique_id(self) -> str:
"""Return a unique ID."""
return "supla-{}-{}".format(
self.channel_data["iodevice"]["gUIDString"].lower(),
self.channel_data["channelNumber"],
)
uid = self.channel_data["iodevice"]["gUIDString"].lower()
channel_number = self.channel_data["channelNumber"]
return f"supla-{uid}-{channel_number}"

Check warning on line 32 in homeassistant/components/supla/entity.py

View check run for this annotation

Codecov / codecov/patch

homeassistant/components/supla/entity.py#L30-L32

Added lines #L30 - L32 were not covered by tests

@property
def name(self) -> str | None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@
@property
def name(self):
"""Return the name of the sensor."""
return "{} {}".format(self._data["water-body-name"], self._condition)
return f"{self._data['water-body-name']} {self._condition}"

Check warning on line 106 in homeassistant/components/swiss_hydrological_data/sensor.py

View check run for this annotation

Codecov / codecov/patch

homeassistant/components/swiss_hydrological_data/sensor.py#L106

Added line #L106 was not covered by tests

@property
def unique_id(self) -> str:
Expand Down
4 changes: 1 addition & 3 deletions homeassistant/components/system_log/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -299,9 +299,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:

hass_path: str = HOMEASSISTANT_PATH[0]
config_dir = hass.config.config_dir
paths_re = re.compile(
r"(?:{})/(.*)".format("|".join([re.escape(x) for x in (hass_path, config_dir)]))
)
paths_re = re.compile(rf"(?:{re.escape(hass_path)}|{re.escape(config_dir)})/(.*)")
handler = LogErrorHandler(
hass, conf[CONF_MAX_ENTRIES], conf[CONF_FIRE_EVENT], paths_re
)
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/ted5000/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,8 @@
mtus = int(doc["LiveData"]["System"]["NumberMTU"])

for mtu in range(1, mtus + 1):
power = int(doc["LiveData"]["Power"]["MTU%d" % mtu]["PowerNow"])
voltage = int(doc["LiveData"]["Voltage"]["MTU%d" % mtu]["VoltageNow"])
power = int(doc["LiveData"]["Power"][f"MTU{mtu}"]["PowerNow"])
voltage = int(doc["LiveData"]["Voltage"][f"MTU{mtu}"]["VoltageNow"])

Check warning on line 140 in homeassistant/components/ted5000/sensor.py

View check run for this annotation

Codecov / codecov/patch

homeassistant/components/ted5000/sensor.py#L139-L140

Added lines #L139 - L140 were not covered by tests

self.data[mtu] = {
UnitOfPower.WATT: power,
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/tellduslive/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -194,4 +194,4 @@
@property
def unique_id(self) -> str:
"""Return a unique ID."""
return "{}-{}-{}".format(*self._id)
return "-".join(self._id)

Check warning on line 197 in homeassistant/components/tellduslive/sensor.py

View check run for this annotation

Codecov / codecov/patch

homeassistant/components/tellduslive/sensor.py#L197

Added line #L197 was not covered by tests
2 changes: 1 addition & 1 deletion homeassistant/components/tensorflow/image_processing.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@

# Draw detected objects
for instance in values:
label = "{} {:.1f}%".format(category, instance["score"])
label = f"{category} {instance['score']:.1f}%"

Check warning on line 327 in homeassistant/components/tensorflow/image_processing.py

View check run for this annotation

Codecov / codecov/patch

homeassistant/components/tensorflow/image_processing.py#L327

Added line #L327 was not covered by tests
draw_box(
draw, instance["box"], img_width, img_height, label, (255, 255, 0)
)
Expand Down
3 changes: 2 additions & 1 deletion homeassistant/components/tomato/device_tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,10 @@ def __init__(self, config):
if port is None:
port = 443 if self.ssl else 80

protocol = "https" if self.ssl else "http"
self.req = requests.Request(
"POST",
"http{}://{}:{}/update.cgi".format("s" if self.ssl else "", host, port),
f"{protocol}://{host}:{port}/update.cgi",
data={"_http_id": http_id, "exec": "devlist"},
auth=requests.auth.HTTPBasicAuth(username, password),
).prepare()
Expand Down
Loading