From c444dbf53ecad9b10d20e6d423bd219be244591a Mon Sep 17 00:00:00 2001 From: Alberto Montes Date: Sun, 15 Sep 2024 07:41:24 +0200 Subject: [PATCH 1/3] Update string formatting to use f-string on components --- homeassistant/components/buienradar/sensor.py | 2 +- homeassistant/components/buienradar/util.py | 2 +- .../components/emoncms_history/__init__.py | 6 ++--- homeassistant/components/graphite/__init__.py | 3 +-- homeassistant/components/hdmi_cec/__init__.py | 2 +- homeassistant/components/home_connect/api.py | 2 +- homeassistant/components/kira/__init__.py | 2 +- .../components/limitlessled/light.py | 4 +-- homeassistant/components/mysensors/light.py | 6 +++-- homeassistant/components/netio/switch.py | 5 ++-- homeassistant/components/numato/__init__.py | 13 +++++----- homeassistant/components/recorder/executor.py | 2 +- .../components/recorder/migration.py | 26 +++++++------------ .../components/sense/binary_sensor.py | 2 +- homeassistant/components/sense/sensor.py | 2 +- .../seven_segments/image_processing.py | 2 +- .../components/shopping_list/intent.py | 6 ++--- .../components/signal_messenger/notify.py | 7 ++--- homeassistant/components/skybeacon/sensor.py | 2 +- homeassistant/components/snips/__init__.py | 2 +- .../components/starlingbank/sensor.py | 5 ++-- homeassistant/components/statsd/__init__.py | 2 +- homeassistant/components/stream/worker.py | 12 +++++---- homeassistant/components/supla/entity.py | 7 +++-- .../swiss_hydrological_data/sensor.py | 2 +- .../components/system_log/__init__.py | 4 +-- homeassistant/components/ted5000/sensor.py | 4 +-- .../components/tellduslive/sensor.py | 2 +- .../components/tensorflow/image_processing.py | 2 +- .../components/tomato/device_tracker.py | 3 ++- homeassistant/components/venstar/__init__.py | 2 +- homeassistant/components/verisure/camera.py | 8 ++---- .../components/viaggiatreno/sensor.py | 2 +- .../components/yeelight/config_flow.py | 4 +-- homeassistant/components/zha/helpers.py | 18 ++++++------- homeassistant/components/zwave_me/light.py | 4 +-- 36 files changed, 79 insertions(+), 100 deletions(-) diff --git a/homeassistant/components/buienradar/sensor.py b/homeassistant/components/buienradar/sensor.py index 69c762c1bc1925..c61d8e10b852a2 100644 --- a/homeassistant/components/buienradar/sensor.py +++ b/homeassistant/components/buienradar/sensor.py @@ -888,7 +888,7 @@ def _load_data(self, data): # noqa: C901 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" self._attr_extra_state_attributes = result diff --git a/homeassistant/components/buienradar/util.py b/homeassistant/components/buienradar/util.py index f089fce89b7405..a7267320de39c7 100644 --- a/homeassistant/components/buienradar/util.py +++ b/homeassistant/components/buienradar/util.py @@ -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: diff --git a/homeassistant/components/emoncms_history/__init__.py b/homeassistant/components/emoncms_history/__init__.py index 7de3a4f2ef8fb9..00af1fec6c6cad 100644 --- a/homeassistant/components/emoncms_history/__init__.py +++ b/homeassistant/components/emoncms_history/__init__.py @@ -86,15 +86,13 @@ def update_emoncms(time): 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()) send_data( conf.get(CONF_URL), conf.get(CONF_API_KEY), str(conf.get(CONF_INPUTNODE)), - payload, + f"{{{payload}}}", ) track_point_in_time( diff --git a/homeassistant/components/graphite/__init__.py b/homeassistant/components/graphite/__init__.py index b0672e1f8536a4..336ca6ba2cb97e 100644 --- a/homeassistant/components/graphite/__init__.py +++ b/homeassistant/components/graphite/__init__.py @@ -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)) ] diff --git a/homeassistant/components/hdmi_cec/__init__.py b/homeassistant/components/hdmi_cec/__init__.py index 9d208b3a2288c5..ac193ad7311374 100644 --- a/homeassistant/components/hdmi_cec/__init__.py +++ b/homeassistant/components/hdmi_cec/__init__.py @@ -367,7 +367,7 @@ def __init__(self, device, logical) -> None: """Initialize the device.""" self._device = device self._logical_address = logical - self.entity_id = "%s.%d" % (DOMAIN, self._logical_address) + self.entity_id = f"{DOMAIN}.{self._logical_address}" self._set_attr_name() self._attr_icon = ICONS_BY_TYPE.get(self._device.type, ICON_UNKNOWN) diff --git a/homeassistant/components/home_connect/api.py b/homeassistant/components/home_connect/api.py index 10dc2d360fa2ac..33b1a462e43290 100644 --- a/homeassistant/components/home_connect/api.py +++ b/homeassistant/components/home_connect/api.py @@ -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, diff --git a/homeassistant/components/kira/__init__.py b/homeassistant/components/kira/__init__.py index b41961f64ee61b..52618a125b6418 100644 --- a/homeassistant/components/kira/__init__.py +++ b/homeassistant/components/kira/__init__.py @@ -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) diff --git a/homeassistant/components/limitlessled/light.py b/homeassistant/components/limitlessled/light.py index 4456d112d0fea3..c6b3301081df61 100644 --- a/homeassistant/components/limitlessled/light.py +++ b/homeassistant/components/limitlessled/light.py @@ -119,13 +119,13 @@ def rewrite_legacy(config: ConfigType) -> ConfigType: 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" 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), } diff --git a/homeassistant/components/mysensors/light.py b/homeassistant/components/mysensors/light.py index e10aee6187ffc0..b03b17e3cb9d56 100644 --- a/homeassistant/components/mysensors/light.py +++ b/homeassistant/components/mysensors/light.py @@ -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 ) @@ -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 ) diff --git a/homeassistant/components/netio/switch.py b/homeassistant/components/netio/switch.py index 54bfef5e1da8dd..5c2b93bcae77b2 100644 --- a/homeassistant/components/netio/switch.py +++ b/homeassistant/components/netio/switch.py @@ -109,7 +109,7 @@ def get(self, request, host): states, consumptions, cumulated_consumptions, start_dates = [], [], [], [] for i in range(1, 5): - out = "output%d" % i + out = f"output{i}" states.append(data.get(f"{out}_state") == STATE_ON) consumptions.append(float(data.get(f"{out}_consumption", 0))) cumulated_consumptions.append( @@ -168,7 +168,8 @@ def turn_off(self, **kwargs: Any) -> None: 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}") self.netio.states[int(self.outlet) - 1] = value self.schedule_update_ha_state() diff --git a/homeassistant/components/numato/__init__.py b/homeassistant/components/numato/__init__.py index 3b99079f9493c6..a2e2327ea57264 100644 --- a/homeassistant/components/numato/__init__.py +++ b/homeassistant/components/numato/__init__.py @@ -185,14 +185,13 @@ def check_port_free(self, device_id: int, port: int, direction: int) -> None: if (device_id, port) not in self.ports_registered: self.ports_registered[(device_id, port)] = direction else: + io = ( + "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: diff --git a/homeassistant/components/recorder/executor.py b/homeassistant/components/recorder/executor.py index 8102c769ac1dfd..6b8192d1e146bd 100644 --- a/homeassistant/components/recorder/executor.py +++ b/homeassistant/components/recorder/executor.py @@ -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, diff --git a/homeassistant/components/recorder/migration.py b/homeassistant/components/recorder/migration.py index df7ff5c4fedfab..9a27a44d706185 100644 --- a/homeassistant/components/recorder/migration.py +++ b/homeassistant/components/recorder/migration.py @@ -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) @@ -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, @@ -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] @@ -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") diff --git a/homeassistant/components/sense/binary_sensor.py b/homeassistant/components/sense/binary_sensor.py index 5640dd19961677..86e6792847a45d 100644 --- a/homeassistant/components/sense/binary_sensor.py +++ b/homeassistant/components/sense/binary_sensor.py @@ -56,7 +56,7 @@ async def _migrate_old_unique_ids(hass, devices): def sense_to_mdi(sense_icon): """Convert sense icon to mdi icon.""" - return "mdi:{}".format(MDI_ICONS.get(sense_icon, "power-plug")) + return "mdi:" + MDI_ICONS.get(sense_icon, "power-plug") class SenseDevice(BinarySensorEntity): diff --git a/homeassistant/components/sense/sensor.py b/homeassistant/components/sense/sensor.py index 129b1262fd05fe..c3a70d7967d5cc 100644 --- a/homeassistant/components/sense/sensor.py +++ b/homeassistant/components/sense/sensor.py @@ -78,7 +78,7 @@ def __init__(self, name, sensor_type): def sense_to_mdi(sense_icon): """Convert sense icon to mdi icon.""" - return "mdi:{}".format(MDI_ICONS.get(sense_icon, "power-plug")) + return "mdi:" + MDI_ICONS.get(sense_icon, "power-plug") async def async_setup_entry( diff --git a/homeassistant/components/seven_segments/image_processing.py b/homeassistant/components/seven_segments/image_processing.py index 7b41a1702c063c..63fd27e0dd04c7 100644 --- a/homeassistant/components/seven_segments/image_processing.py +++ b/homeassistant/components/seven_segments/image_processing.py @@ -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", diff --git a/homeassistant/components/shopping_list/intent.py b/homeassistant/components/shopping_list/intent.py index d45085be5fa8e8..84ea3971293688 100644 --- a/homeassistant/components/shopping_list/intent.py +++ b/homeassistant/components/shopping_list/intent.py @@ -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 diff --git a/homeassistant/components/signal_messenger/notify.py b/homeassistant/components/signal_messenger/notify.py index 9321bc3232fcd0..03f95a4779b231 100644 --- a/homeassistant/components/signal_messenger/notify.py +++ b/homeassistant/components/signal_messenger/notify.py @@ -166,12 +166,9 @@ 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, - ) + f"Attachment too large (Content-Length reports {content_length}). Max size: {CONF_MAX_ALLOWED_DOWNLOAD_SIZE_BYTES} bytes" ) size = 0 diff --git a/homeassistant/components/skybeacon/sensor.py b/homeassistant/components/skybeacon/sensor.py index a3a5eb48098640..beb12e8598ee46 100644 --- a/homeassistant/components/skybeacon/sensor.py +++ b/homeassistant/components/skybeacon/sensor.py @@ -184,7 +184,7 @@ def _update(self, handle, value): value[2], value[1], ) - self.data["temp"] = float("%d.%d" % (value[0], value[2])) + self.data["temp"] = float(f"{value[0]}.{value[2]}") self.data["humid"] = value[1] def terminate(self): diff --git a/homeassistant/components/snips/__init__.py b/homeassistant/components/snips/__init__.py index 4731a0f324a307..70837b95ec535a 100644 --- a/homeassistant/components/snips/__init__.py +++ b/homeassistant/components/snips/__init__.py @@ -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"]} diff --git a/homeassistant/components/starlingbank/sensor.py b/homeassistant/components/starlingbank/sensor.py index fd351416c288b1..282323d8b7bd50 100644 --- a/homeassistant/components/starlingbank/sensor.py +++ b/homeassistant/components/starlingbank/sensor.py @@ -92,9 +92,8 @@ def __init__(self, starling_account, account_name, balance_data_type): @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}" @property def native_value(self): diff --git a/homeassistant/components/statsd/__init__.py b/homeassistant/components/statsd/__init__.py index efe1c8180257c9..50b74b20028734 100644 --- a/homeassistant/components/statsd/__init__.py +++ b/homeassistant/components/statsd/__init__.py @@ -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)): diff --git a/homeassistant/components/stream/worker.py b/homeassistant/components/stream/worker.py index 354cc476186367..0d72a9b081871c 100644 --- a/homeassistant/components/stream/worker.py +++ b/homeassistant/components/stream/worker.py @@ -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 + else 0 + ), ) if last_part: # If we've written the last part, we can close the memory_file. diff --git a/homeassistant/components/supla/entity.py b/homeassistant/components/supla/entity.py index fa257e39a06cc5..446d67d19d64e9 100644 --- a/homeassistant/components/supla/entity.py +++ b/homeassistant/components/supla/entity.py @@ -27,10 +27,9 @@ def channel_data(self): @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}" @property def name(self) -> str | None: diff --git a/homeassistant/components/swiss_hydrological_data/sensor.py b/homeassistant/components/swiss_hydrological_data/sensor.py index c67045521b5cf7..3d88182eaa471e 100644 --- a/homeassistant/components/swiss_hydrological_data/sensor.py +++ b/homeassistant/components/swiss_hydrological_data/sensor.py @@ -103,7 +103,7 @@ def __init__(self, hydro_data, station, condition): @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}" @property def unique_id(self) -> str: diff --git a/homeassistant/components/system_log/__init__.py b/homeassistant/components/system_log/__init__.py index 0749f87a67fde8..22950aa9f1ecf1 100644 --- a/homeassistant/components/system_log/__init__.py +++ b/homeassistant/components/system_log/__init__.py @@ -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 ) diff --git a/homeassistant/components/ted5000/sensor.py b/homeassistant/components/ted5000/sensor.py index 68f4520a7e31c4..26f469349b463c 100644 --- a/homeassistant/components/ted5000/sensor.py +++ b/homeassistant/components/ted5000/sensor.py @@ -136,8 +136,8 @@ def update(self) -> None: 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"]) self.data[mtu] = { UnitOfPower.WATT: power, diff --git a/homeassistant/components/tellduslive/sensor.py b/homeassistant/components/tellduslive/sensor.py index 70c83bb0038962..e588ea6318fa99 100644 --- a/homeassistant/components/tellduslive/sensor.py +++ b/homeassistant/components/tellduslive/sensor.py @@ -194,4 +194,4 @@ def native_value(self): @property def unique_id(self) -> str: """Return a unique ID.""" - return "{}-{}-{}".format(*self._id) + return "-".join(self._id) diff --git a/homeassistant/components/tensorflow/image_processing.py b/homeassistant/components/tensorflow/image_processing.py index f13c0b24d0b611..523d6ada84418b 100644 --- a/homeassistant/components/tensorflow/image_processing.py +++ b/homeassistant/components/tensorflow/image_processing.py @@ -324,7 +324,7 @@ def _save_image(self, image, matches, paths): # Draw detected objects for instance in values: - label = "{} {:.1f}%".format(category, instance["score"]) + label = f"{category} {instance['score']:.1f}%" draw_box( draw, instance["box"], img_width, img_height, label, (255, 255, 0) ) diff --git a/homeassistant/components/tomato/device_tracker.py b/homeassistant/components/tomato/device_tracker.py index f1527f52c646a6..b19f87a8b41654 100644 --- a/homeassistant/components/tomato/device_tracker.py +++ b/homeassistant/components/tomato/device_tracker.py @@ -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() diff --git a/homeassistant/components/venstar/__init__.py b/homeassistant/components/venstar/__init__.py index cbcfd3dff90d05..91b6846f77c4b8 100644 --- a/homeassistant/components/venstar/__init__.py +++ b/homeassistant/components/venstar/__init__.py @@ -89,5 +89,5 @@ def device_info(self) -> DeviceInfo: name=self._client.name, manufacturer="Venstar", model=f"{self._client.model}-{self._client.get_type()}", - sw_version="{}.{}".format(*(self._client.get_firmware_ver())), + sw_version=f"{self._client.get_firmware_ver()[0]}.{self._client.get_firmware_ver()[1]}", ) diff --git a/homeassistant/components/verisure/camera.py b/homeassistant/components/verisure/camera.py index 50606a49eab1a2..70cd436d24cf1c 100644 --- a/homeassistant/components/verisure/camera.py +++ b/homeassistant/components/verisure/camera.py @@ -110,9 +110,7 @@ def check_imagelist(self) -> None: return LOGGER.debug("Download new image %s", new_image_id) - new_image_path = os.path.join( - self._directory_path, "{}{}".format(new_image_id, ".jpg") - ) + new_image_path = os.path.join(self._directory_path, f"{new_image_id}.jpg") new_image_url = new_image["contentUrl"] self.coordinator.verisure.download_image(new_image_url, new_image_path) LOGGER.debug("Old image_id=%s", self._image_id) @@ -123,9 +121,7 @@ def check_imagelist(self) -> None: def delete_image(self, _=None) -> None: """Delete an old image.""" - remove_image = os.path.join( - self._directory_path, "{}{}".format(self._image_id, ".jpg") - ) + remove_image = os.path.join(self._directory_path, f"{self._image_id}.jpg") try: os.remove(remove_image) LOGGER.debug("Deleting old image %s", remove_image) diff --git a/homeassistant/components/viaggiatreno/sensor.py b/homeassistant/components/viaggiatreno/sensor.py index 1ea12ed6a41897..cb652270c69320 100644 --- a/homeassistant/components/viaggiatreno/sensor.py +++ b/homeassistant/components/viaggiatreno/sensor.py @@ -174,7 +174,7 @@ async def async_update(self) -> None: self._state = NO_INFORMATION_STRING self._unit = "" else: - self._state = "Error: {}".format(res["error"]) + self._state = f"Error: {res['error']}" self._unit = "" else: for i in MONITORED_INFO: diff --git a/homeassistant/components/yeelight/config_flow.py b/homeassistant/components/yeelight/config_flow.py index b22774c68c3a59..cafed622300565 100644 --- a/homeassistant/components/yeelight/config_flow.py +++ b/homeassistant/components/yeelight/config_flow.py @@ -85,9 +85,7 @@ async def async_step_zeroconf( ) -> ConfigFlowResult: """Handle discovery from zeroconf.""" self._discovered_ip = discovery_info.host - await self.async_set_unique_id( - "{0:#0{1}x}".format(int(discovery_info.name[-26:-18]), 18) - ) + await self.async_set_unique_id(f"{int(discovery_info.name[-26:-18]):#018x}") return await self._async_handle_discovery_with_unique_id() async def async_step_ssdp( diff --git a/homeassistant/components/zha/helpers.py b/homeassistant/components/zha/helpers.py index 4ca2f5d172bf0b..dc999f13693573 100644 --- a/homeassistant/components/zha/helpers.py +++ b/homeassistant/components/zha/helpers.py @@ -617,9 +617,11 @@ def handle_raw_device_initialized(self, event: RawDeviceInitializedEvent) -> Non ATTR_NWK: str(event.device_info.nwk), ATTR_IEEE: str(event.device_info.ieee), DEVICE_PAIRING_STATUS: event.device_info.pairing_status.name, - ATTR_MODEL: event.device_info.model - if event.device_info.model - else UNKNOWN_MODEL, + ATTR_MODEL: ( + event.device_info.model + if event.device_info.model + else UNKNOWN_MODEL + ), ATTR_MANUFACTURER: manuf if manuf else UNKNOWN_MANUFACTURER, ATTR_SIGNATURE: event.device_info.signature, }, @@ -922,9 +924,7 @@ def __init__(self, hass: HomeAssistant, gateway: ZHAGatewayProxy) -> None: hass_path: str = HOMEASSISTANT_PATH[0] config_dir = self.hass.config.config_dir self.paths_re = re.compile( - r"(?:{})/(.*)".format( - "|".join([re.escape(x) for x in (hass_path, config_dir)]) - ) + rf"(?:{re.escape(hass_path)}|{re.escape(config_dir)})/(.*)" ) def emit(self, record: LogRecord) -> None: @@ -1025,9 +1025,9 @@ def cluster_command_schema_to_vol_schema(schema: CommandSchema) -> vol.Schema: """Convert a cluster command schema to a voluptuous schema.""" return vol.Schema( { - vol.Optional(field.name) - if field.optional - else vol.Required(field.name): schema_type_to_vol(field.type) + ( + vol.Optional(field.name) if field.optional else vol.Required(field.name) + ): schema_type_to_vol(field.type) for field in schema.fields } ) diff --git a/homeassistant/components/zwave_me/light.py b/homeassistant/components/zwave_me/light.py index 2289fe7b115c15..9a76a02480625c 100644 --- a/homeassistant/components/zwave_me/light.py +++ b/homeassistant/components/zwave_me/light.py @@ -84,8 +84,8 @@ def turn_on(self, **kwargs: Any) -> None: self.device.id, f"exact?level={round(brightness / 2.55)}" ) return - cmd = "exact?red={}&green={}&blue={}" - cmd = cmd.format(*color) if any(color) else cmd.format(*(255, 255, 255)) + red, green, blue = color if any(color) else (255, 255, 255) + cmd = f"exact?red={red}&green={green}&blue={blue}" self.controller.zwave_api.send_command(self.device.id, cmd) @property From ca5a568be94d841495980a7d9727d846dde5f5a1 Mon Sep 17 00:00:00 2001 From: Alberto Montes Date: Thu, 19 Sep 2024 10:59:59 +0200 Subject: [PATCH 2/3] Update code given review feedback --- homeassistant/components/sense/binary_sensor.py | 2 +- homeassistant/components/signal_messenger/notify.py | 4 +++- homeassistant/components/venstar/__init__.py | 3 ++- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/homeassistant/components/sense/binary_sensor.py b/homeassistant/components/sense/binary_sensor.py index 86e6792847a45d..8317f8458b3449 100644 --- a/homeassistant/components/sense/binary_sensor.py +++ b/homeassistant/components/sense/binary_sensor.py @@ -56,7 +56,7 @@ async def _migrate_old_unique_ids(hass, devices): def sense_to_mdi(sense_icon): """Convert sense icon to mdi icon.""" - return "mdi:" + MDI_ICONS.get(sense_icon, "power-plug") + return f"mdi:{MDI_ICONS.get(sense_icon, "power-plug")}" class SenseDevice(BinarySensorEntity): diff --git a/homeassistant/components/signal_messenger/notify.py b/homeassistant/components/signal_messenger/notify.py index 03f95a4779b231..53a255da5ff8c7 100644 --- a/homeassistant/components/signal_messenger/notify.py +++ b/homeassistant/components/signal_messenger/notify.py @@ -168,7 +168,9 @@ def get_attachments_as_bytes( ): content_length = int(str(resp.headers.get("Content-Length"))) raise ValueError( # noqa: TRY301 - f"Attachment too large (Content-Length reports {content_length}). Max size: {CONF_MAX_ALLOWED_DOWNLOAD_SIZE_BYTES} bytes" + "Attachment too large (Content-Length reports " + f"{content_length}). Max size: " + f"{CONF_MAX_ALLOWED_DOWNLOAD_SIZE_BYTES} bytes" ) size = 0 diff --git a/homeassistant/components/venstar/__init__.py b/homeassistant/components/venstar/__init__.py index 91b6846f77c4b8..563a974fad6fcd 100644 --- a/homeassistant/components/venstar/__init__.py +++ b/homeassistant/components/venstar/__init__.py @@ -84,10 +84,11 @@ def _handle_coordinator_update(self) -> None: @property def device_info(self) -> DeviceInfo: """Return the device information for this entity.""" + fw_ver_major, fw_ver_minor = self._client.get_firmware_ver() return DeviceInfo( identifiers={(DOMAIN, self._config.entry_id)}, name=self._client.name, manufacturer="Venstar", model=f"{self._client.model}-{self._client.get_type()}", - sw_version=f"{self._client.get_firmware_ver()[0]}.{self._client.get_firmware_ver()[1]}", + sw_version=f"{fw_ver_major}.{fw_ver_minor}", ) From d7b517d07e4333dceef07d1f8f7c67ae51ffb02f Mon Sep 17 00:00:00 2001 From: Martin Hjelmare Date: Thu, 19 Sep 2024 11:07:18 +0200 Subject: [PATCH 3/3] Use f-string --- homeassistant/components/sense/sensor.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/homeassistant/components/sense/sensor.py b/homeassistant/components/sense/sensor.py index c3a70d7967d5cc..bc9dd470f5eed7 100644 --- a/homeassistant/components/sense/sensor.py +++ b/homeassistant/components/sense/sensor.py @@ -78,7 +78,7 @@ def __init__(self, name, sensor_type): def sense_to_mdi(sense_icon): """Convert sense icon to mdi icon.""" - return "mdi:" + MDI_ICONS.get(sense_icon, "power-plug") + return f"mdi:{MDI_ICONS.get(sense_icon, 'power-plug')}" async def async_setup_entry(