From fa4fa304617153cb7ec320662c07a7555575ff63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Fri, 3 Jan 2020 15:47:06 +0200 Subject: [PATCH] Various string cleanups (#30435) * Remove some unnecessary string concatenations * Replace some simple str.formats with f-strings * Replace some string concatenations with f-strings --- homeassistant/__main__.py | 14 ++--- homeassistant/components/apns/notify.py | 2 +- .../components/braviatv/media_player.py | 2 +- homeassistant/components/cloud/__init__.py | 2 +- homeassistant/components/darksky/sensor.py | 2 +- homeassistant/components/ebusd/__init__.py | 2 +- .../components/ecoal_boiler/__init__.py | 2 +- .../components/ecoal_boiler/switch.py | 2 +- homeassistant/components/egardia/__init__.py | 2 +- homeassistant/components/fibaro/__init__.py | 2 +- .../components/hangouts/hangouts_bot.py | 8 +-- homeassistant/components/hook/switch.py | 6 +- .../huawei_router/device_tracker.py | 2 +- homeassistant/components/icloud/__init__.py | 4 +- homeassistant/components/insteon/__init__.py | 2 +- .../components/itunes/media_player.py | 12 ++-- homeassistant/components/kodi/media_player.py | 2 +- .../components/konnected/__init__.py | 2 +- .../components/life360/device_tracker.py | 2 +- homeassistant/components/lifx/light.py | 2 +- .../components/netatmo/binary_sensor.py | 4 +- homeassistant/components/netatmo/camera.py | 4 +- .../components/netgear/device_tracker.py | 4 +- .../components/octoprint/__init__.py | 12 ++-- homeassistant/components/onewire/sensor.py | 2 +- homeassistant/components/plant/__init__.py | 18 +++--- homeassistant/components/plex/media_player.py | 2 +- .../components/raspihats/__init__.py | 2 +- homeassistant/components/raspihats/switch.py | 6 +- .../components/samsungtv/media_player.py | 2 +- homeassistant/components/sensibo/climate.py | 2 +- .../components/seventeentrack/sensor.py | 2 +- .../components/sky_hub/device_tracker.py | 7 +-- homeassistant/components/smappee/__init__.py | 2 +- .../components/smartthings/__init__.py | 2 +- .../components/smartthings/smartapp.py | 2 +- .../components/soundtouch/media_player.py | 2 +- homeassistant/components/startca/sensor.py | 2 +- .../components/tank_utility/sensor.py | 2 +- homeassistant/components/temper/sensor.py | 2 +- .../components/wunderground/sensor.py | 8 +-- homeassistant/components/x10/light.py | 10 ++-- homeassistant/components/yeelight/light.py | 2 +- homeassistant/components/zha/api.py | 2 +- .../components/zha/core/channels/__init__.py | 4 +- homeassistant/components/zha/core/device.py | 2 +- homeassistant/components/zha/entity.py | 2 +- .../components/zhong_hong/climate.py | 4 +- homeassistant/components/zwave/cover.py | 2 +- homeassistant/config.py | 4 +- homeassistant/const.py | 4 +- homeassistant/core.py | 16 ++---- homeassistant/data_entry_flow.py | 4 +- homeassistant/helpers/__init__.py | 2 +- homeassistant/helpers/check_config.py | 4 +- homeassistant/helpers/config_validation.py | 42 +++++++------- homeassistant/helpers/discovery.py | 4 +- homeassistant/helpers/entity.py | 2 +- homeassistant/helpers/entity_platform.py | 12 +--- homeassistant/helpers/entity_registry.py | 5 +- homeassistant/helpers/icon.py | 2 +- homeassistant/helpers/intent.py | 2 +- homeassistant/helpers/script.py | 6 +- homeassistant/helpers/service.py | 2 +- homeassistant/helpers/template.py | 4 +- homeassistant/helpers/translation.py | 2 +- homeassistant/scripts/__init__.py | 2 +- homeassistant/scripts/check_config.py | 2 +- homeassistant/scripts/macos/__init__.py | 6 +- homeassistant/setup.py | 4 +- homeassistant/util/dt.py | 4 +- homeassistant/util/ruamel_yaml.py | 2 +- homeassistant/util/unit_system.py | 8 +-- script/gen_requirements_all.py | 6 +- script/hassfest/dependencies.py | 5 +- script/hassfest/model.py | 4 +- script/inspect_schemas.py | 5 +- script/lazytox.py | 5 +- tests/common.py | 55 ++++++------------- tests/components/hddtemp/test_sensor.py | 2 +- tests/components/light/test_init.py | 2 +- tests/components/tradfri/test_light.py | 10 ++-- tests/components/uk_transport/test_sensor.py | 4 +- .../unifi_direct/test_device_tracker.py | 4 +- .../components/vacuum/test_device_trigger.py | 8 +-- tests/components/webhook/test_init.py | 14 ++--- tests/components/withings/common.py | 9 ++- tests/components/xiaomi_miio/test_vacuum.py | 4 +- tests/components/yessssms/test_notify.py | 4 +- tests/components/yweather/test_sensor.py | 2 +- tests/components/zeroconf/test_init.py | 4 +- tests/components/zha/test_sensor.py | 6 +- tests/components/zwave/test_init.py | 18 +++--- tests/conftest.py | 7 +-- tests/helpers/test_config_entry_flow.py | 4 +- tests/helpers/test_entity_component.py | 4 +- tests/helpers/test_entity_platform.py | 4 +- tests/helpers/test_storage.py | 2 +- tests/helpers/test_temperature.py | 2 +- tests/helpers/test_template.py | 6 +- tests/test_bootstrap.py | 2 +- tests/test_config.py | 4 +- tests/test_core.py | 9 ++- tests/test_loader.py | 2 +- tests/test_setup.py | 2 +- 105 files changed, 241 insertions(+), 314 deletions(-) diff --git a/homeassistant/__main__.py b/homeassistant/__main__.py index a0243e2dd8c8c2..5398c3d5c55973 100644 --- a/homeassistant/__main__.py +++ b/homeassistant/__main__.py @@ -55,10 +55,8 @@ def ensure_config_path(config_dir: str) -> None: if not os.path.isdir(config_dir): if config_dir != config_util.get_default_config_dir(): print( - ( - "Fatal Error: Specified configuration directory does " - "not exist {} " - ).format(config_dir) + f"Fatal Error: Specified configuration directory {config_dir} " + "does not exist" ) sys.exit(1) @@ -66,10 +64,8 @@ def ensure_config_path(config_dir: str) -> None: os.mkdir(config_dir) except OSError: print( - ( - "Fatal Error: Unable to create default configuration " - "directory {} " - ).format(config_dir) + "Fatal Error: Unable to create default configuration " + f"directory {config_dir}" ) sys.exit(1) @@ -78,7 +74,7 @@ def ensure_config_path(config_dir: str) -> None: try: os.mkdir(lib_dir) except OSError: - print("Fatal Error: Unable to create library directory {}".format(lib_dir)) + print(f"Fatal Error: Unable to create library directory {lib_dir}") sys.exit(1) diff --git a/homeassistant/components/apns/notify.py b/homeassistant/components/apns/notify.py index 990598508afddb..febe344a9c46bf 100644 --- a/homeassistant/components/apns/notify.py +++ b/homeassistant/components/apns/notify.py @@ -150,7 +150,7 @@ def __init__(self, hass, app_name, topic, sandbox, cert_file): self.app_name = app_name self.sandbox = sandbox self.certificate = cert_file - self.yaml_path = hass.config.path(app_name + "_" + APNS_DEVICES) + self.yaml_path = hass.config.path(f"{app_name}_{APNS_DEVICES}") self.devices = {} self.device_states = {} self.topic = topic diff --git a/homeassistant/components/braviatv/media_player.py b/homeassistant/components/braviatv/media_player.py index d0458541f7bee8..ef0640c8e87257 100644 --- a/homeassistant/components/braviatv/media_player.py +++ b/homeassistant/components/braviatv/media_player.py @@ -291,7 +291,7 @@ def media_title(self): if self._channel_name is not None: return_value = self._channel_name if self._program_name is not None: - return_value = return_value + ": " + self._program_name + return_value = f"{return_value}: {self._program_name}" return return_value @property diff --git a/homeassistant/components/cloud/__init__.py b/homeassistant/components/cloud/__init__.py index 6d9b70051f5dab..4799a82979f3ae 100644 --- a/homeassistant/components/cloud/__init__.py +++ b/homeassistant/components/cloud/__init__.py @@ -158,7 +158,7 @@ def async_remote_ui_url(hass) -> str: if not hass.data[DOMAIN].remote.instance_domain: raise CloudNotAvailable - return "https://" + hass.data[DOMAIN].remote.instance_domain + return f"https://{hass.data[DOMAIN].remote.instance_domain}" def is_cloudhook_request(request): diff --git a/homeassistant/components/darksky/sensor.py b/homeassistant/components/darksky/sensor.py index 5b6da5d11bb53d..9f99b37a2013c5 100644 --- a/homeassistant/components/darksky/sensor.py +++ b/homeassistant/components/darksky/sensor.py @@ -750,7 +750,7 @@ def get_state(self, data): for i, alert in enumerate(data): for attr in ALERTS_ATTRS: if multiple_alerts: - dkey = attr + "_" + str(i) + dkey = f"{attr}_{i!s}" else: dkey = attr alerts[dkey] = getattr(alert, attr) diff --git a/homeassistant/components/ebusd/__init__.py b/homeassistant/components/ebusd/__init__.py index e4d0bdbcdb1ac1..eafa42ba22aa73 100644 --- a/homeassistant/components/ebusd/__init__.py +++ b/homeassistant/components/ebusd/__init__.py @@ -34,7 +34,7 @@ def verify_ebusd_config(config): circuit = config[CONF_CIRCUIT] for condition in config[CONF_MONITORED_CONDITIONS]: if condition not in SENSOR_TYPES[circuit]: - raise vol.Invalid("Condition '" + condition + "' not in '" + circuit + "'.") + raise vol.Invalid(f"Condition '{condition}' not in '{circuit}'.") return config diff --git a/homeassistant/components/ecoal_boiler/__init__.py b/homeassistant/components/ecoal_boiler/__init__.py index 608e4a59a3fecc..b0ca7aec5ccde7 100644 --- a/homeassistant/components/ecoal_boiler/__init__.py +++ b/homeassistant/components/ecoal_boiler/__init__.py @@ -18,7 +18,7 @@ _LOGGER = logging.getLogger(__name__) DOMAIN = "ecoal_boiler" -DATA_ECOAL_BOILER = "data_" + DOMAIN +DATA_ECOAL_BOILER = f"data_{DOMAIN}" DEFAULT_USERNAME = "admin" DEFAULT_PASSWORD = "admin" diff --git a/homeassistant/components/ecoal_boiler/switch.py b/homeassistant/components/ecoal_boiler/switch.py index 9f286e625a5206..00bfd7f3e5b976 100644 --- a/homeassistant/components/ecoal_boiler/switch.py +++ b/homeassistant/components/ecoal_boiler/switch.py @@ -38,7 +38,7 @@ def __init__(self, ecoal_contr, name, state_attr): # set_() # as attribute name in status instance: # status. - self._contr_set_fun = getattr(self._ecoal_contr, "set_" + state_attr) + self._contr_set_fun = getattr(self._ecoal_contr, f"set_{state_attr}") # No value set, will be read from controller instead self._state = None diff --git a/homeassistant/components/egardia/__init__.py b/homeassistant/components/egardia/__init__.py index efe477364791d9..770db1d236b76c 100644 --- a/homeassistant/components/egardia/__init__.py +++ b/homeassistant/components/egardia/__init__.py @@ -110,7 +110,7 @@ def setup(hass, config): bound = server.bind() if not bound: raise OSError( - "Binding error occurred while " + "starting EgardiaServer." + "Binding error occurred while starting EgardiaServer." ) hass.data[EGARDIA_SERVER] = server server.start() diff --git a/homeassistant/components/fibaro/__init__.py b/homeassistant/components/fibaro/__init__.py index aeb7c0879e0c1c..32d8f328ef84f1 100644 --- a/homeassistant/components/fibaro/__init__.py +++ b/homeassistant/components/fibaro/__init__.py @@ -268,7 +268,7 @@ def _read_devices(self): else: room_name = self._room_map[device.roomID].name device.room_name = room_name - device.friendly_name = room_name + " " + device.name + device.friendly_name = f"{room_name} {device.name}" device.ha_id = "{}_{}_{}".format( slugify(room_name), slugify(device.name), device.id ) diff --git a/homeassistant/components/hangouts/hangouts_bot.py b/homeassistant/components/hangouts/hangouts_bot.py index 8575a547a9c8b5..fd14ec0b0949fe 100644 --- a/homeassistant/components/hangouts/hangouts_bot.py +++ b/homeassistant/components/hangouts/hangouts_bot.py @@ -86,15 +86,15 @@ def async_update_conversation_commands(self): conv_id = self._resolve_conversation_id(conversation) if conv_id is not None: conversations.append(conv_id) - data["_" + CONF_CONVERSATIONS] = conversations + data[f"_{CONF_CONVERSATIONS}"] = conversations elif self._default_conv_ids: - data["_" + CONF_CONVERSATIONS] = self._default_conv_ids + data[f"_{CONF_CONVERSATIONS}"] = self._default_conv_ids else: - data["_" + CONF_CONVERSATIONS] = [ + data[f"_{CONF_CONVERSATIONS}"] = [ conv.id_ for conv in self._conversation_list.get_all() ] - for conv_id in data["_" + CONF_CONVERSATIONS]: + for conv_id in data[f"_{CONF_CONVERSATIONS}"]: if conv_id not in self._conversation_intents: self._conversation_intents[conv_id] = {} diff --git a/homeassistant/components/hook/switch.py b/homeassistant/components/hook/switch.py index 14c4d4ba662991..582dc61af14fba 100644 --- a/homeassistant/components/hook/switch.py +++ b/homeassistant/components/hook/switch.py @@ -21,12 +21,10 @@ vol.Exclusive( CONF_PASSWORD, "hook_secret", - msg="hook: provide " + "username/password OR token", + msg="hook: provide username/password OR token", ): cv.string, vol.Exclusive( - CONF_TOKEN, - "hook_secret", - msg="hook: provide " + "username/password OR token", + CONF_TOKEN, "hook_secret", msg="hook: provide username/password OR token", ): cv.string, vol.Inclusive(CONF_USERNAME, "hook_auth"): cv.string, vol.Inclusive(CONF_PASSWORD, "hook_auth"): cv.string, diff --git a/homeassistant/components/huawei_router/device_tracker.py b/homeassistant/components/huawei_router/device_tracker.py index 4b52060e425ea8..be34b26be0d4b3 100644 --- a/homeassistant/components/huawei_router/device_tracker.py +++ b/homeassistant/components/huawei_router/device_tracker.py @@ -88,7 +88,7 @@ def _update_info(self): _LOGGER.debug( "Active clients: %s", - "\n".join((client.mac + " " + client.name) for client in active_clients), + "\n".join(f"{client.mac} {client.name}" for client in active_clients), ) return True diff --git a/homeassistant/components/icloud/__init__.py b/homeassistant/components/icloud/__init__.py index c59f4098951ad3..e983f5fac2215f 100644 --- a/homeassistant/components/icloud/__init__.py +++ b/homeassistant/components/icloud/__init__.py @@ -216,7 +216,7 @@ def _get_account(account_identifier: str) -> any: if icloud_account is None: raise Exception( - "No iCloud account with username or name " + account_identifier + f"No iCloud account with username or name {account_identifier}" ) return icloud_account @@ -430,7 +430,7 @@ def get_devices_with_name(self, name: str) -> [any]: if slugify(device.name.replace(" ", "", 99)) == name_slug: result.append(device) if not result: - raise Exception("No device with name " + name) + raise Exception(f"No device with name {name}") return result @property diff --git a/homeassistant/components/insteon/__init__.py b/homeassistant/components/insteon/__init__.py index 11f224dbfccaec..df6fa626a4fa79 100644 --- a/homeassistant/components/insteon/__init__.py +++ b/homeassistant/components/insteon/__init__.py @@ -614,7 +614,7 @@ def name(self): # Get an extension label if there is one extension = self._get_label() if extension: - extension = " " + extension + extension = f" {extension}" name = "{:s} {:s}{:s}".format( description, self._insteon_device.address.human, extension ) diff --git a/homeassistant/components/itunes/media_player.py b/homeassistant/components/itunes/media_player.py index 112a9c609d836a..327cbf5e9ac11d 100644 --- a/homeassistant/components/itunes/media_player.py +++ b/homeassistant/components/itunes/media_player.py @@ -110,7 +110,7 @@ def _request(self, method, path, params=None): def _command(self, named_command): """Make a request for a controlling command.""" - return self._request("PUT", "/" + named_command) + return self._request("PUT", f"/{named_command}") def now_playing(self): """Return the current state.""" @@ -168,7 +168,7 @@ def play_playlist(self, playlist_id_or_name): def artwork_url(self): """Return a URL of the current track's album art.""" - return self._base_url + "/artwork" + return f"{self._base_url}/artwork" def airplay_devices(self): """Return a list of AirPlay devices.""" @@ -176,17 +176,17 @@ def airplay_devices(self): def airplay_device(self, device_id): """Return an AirPlay device.""" - return self._request("GET", "/airplay_devices/" + device_id) + return self._request("GET", f"/airplay_devices/{device_id}") def toggle_airplay_device(self, device_id, toggle): """Toggle airplay device on or off, id, toggle True or False.""" command = "on" if toggle else "off" - path = "/airplay_devices/" + device_id + "/" + command + path = f"/airplay_devices/{device_id}/{command}" return self._request("PUT", path) def set_volume_airplay_device(self, device_id, level): """Set volume, returns current state of device, id,level 0-100.""" - path = "/airplay_devices/" + device_id + "/volume" + path = f"/airplay_devices/{device_id}/volume" return self._request("PUT", path, {"level": level}) @@ -431,7 +431,7 @@ def update_state(self, state_hash): if "name" in state_hash: name = state_hash.get("name", "") - self.device_name = (name + " AirTunes Speaker").strip() + self.device_name = f"{name} AirTunes Speaker".strip() if "kind" in state_hash: self.kind = state_hash.get("kind", None) diff --git a/homeassistant/components/kodi/media_player.py b/homeassistant/components/kodi/media_player.py index 71418927ed21c4..13aa18d01adce6 100644 --- a/homeassistant/components/kodi/media_player.py +++ b/homeassistant/components/kodi/media_player.py @@ -963,7 +963,7 @@ async def async_find_album(self, album_name, artist_name=""): @staticmethod def _find(key_word, words): key_word = key_word.split(" ") - patt = [re.compile("(^| )" + k + "( |$)", re.IGNORECASE) for k in key_word] + patt = [re.compile(f"(^| ){k}( |$)", re.IGNORECASE) for k in key_word] out = [[i, 0] for i in range(len(words))] for i in range(len(words)): diff --git a/homeassistant/components/konnected/__init__.py b/homeassistant/components/konnected/__init__.py index 624d359e154637..28e62c322ad824 100644 --- a/homeassistant/components/konnected/__init__.py +++ b/homeassistant/components/konnected/__init__.py @@ -488,7 +488,7 @@ async def get(self, request: Request, device_id) -> Response: device = data[CONF_DEVICES][device_id] if not device: return self.json_message( - "Device " + device_id + " not configured", status_code=HTTP_NOT_FOUND + f"Device {device_id} not configured", status_code=HTTP_NOT_FOUND ) try: diff --git a/homeassistant/components/life360/device_tracker.py b/homeassistant/components/life360/device_tracker.py index ddd562ebfac8e9..b2ba1ca31640c0 100644 --- a/homeassistant/components/life360/device_tracker.py +++ b/homeassistant/components/life360/device_tracker.py @@ -162,7 +162,7 @@ def _err(self, key, err_msg): msg = f"{key}: {err_msg}" if _errs >= self._error_threshold: if _errs == self._max_errs: - msg = "Suppressing further errors until OK: " + msg + msg = f"Suppressing further errors until OK: {msg}" _LOGGER.error(msg) elif _errs >= self._warning_threshold: _LOGGER.warning(msg) diff --git a/homeassistant/components/lifx/light.py b/homeassistant/components/lifx/light.py index aa63be04f0d3f0..4e845a07854208 100644 --- a/homeassistant/components/lifx/light.py +++ b/homeassistant/components/lifx/light.py @@ -562,7 +562,7 @@ def effect(self): """Return the name of the currently running effect.""" effect = self.effects_conductor.effect(self.bulb) if effect: - return "lifx_effect_" + effect.name + return f"lifx_effect_{effect.name}" return None async def update_hass(self, now=None): diff --git a/homeassistant/components/netatmo/binary_sensor.py b/homeassistant/components/netatmo/binary_sensor.py index 06097ed852d9fa..a449b7bb43daef 100644 --- a/homeassistant/components/netatmo/binary_sensor.py +++ b/homeassistant/components/netatmo/binary_sensor.py @@ -155,9 +155,9 @@ def __init__( else: self._name = camera_name if module_name: - self._name += " / " + module_name + self._name += f" / {module_name}" self._sensor_name = sensor - self._name += " " + sensor + self._name += f" {sensor}" self._cameratype = camera_type self._state = None diff --git a/homeassistant/components/netatmo/camera.py b/homeassistant/components/netatmo/camera.py index 1713265a014c9a..546a5da3c152e8 100644 --- a/homeassistant/components/netatmo/camera.py +++ b/homeassistant/components/netatmo/camera.py @@ -106,7 +106,7 @@ def __init__(self, data, camera_name, home, camera_type, verify_ssl, quality): self._camera_name = camera_name self._home = home if home: - self._name = home + " / " + camera_name + self._name = f"{home} / {camera_name}" else: self._name = camera_name self._cameratype = camera_type @@ -383,7 +383,7 @@ def _set_light_mode(self, mode): """Set light mode ('auto', 'on', 'off').""" if self.model == "Presence": try: - config = '{"mode":"' + mode + '"}' + config = f'{{"mode":"{mode}"}}' if self._localurl: requests.get( f"{self._localurl}/command/floodlight_set_config?config={config}", diff --git a/homeassistant/components/netgear/device_tracker.py b/homeassistant/components/netgear/device_tracker.py index d556e83ca13707..3e87bcac53c3ec 100644 --- a/homeassistant/components/netgear/device_tracker.py +++ b/homeassistant/components/netgear/device_tracker.py @@ -116,7 +116,7 @@ def scan_devices(self): self.tracked_accesspoints and dev.conn_ap_mac in self.tracked_accesspoints ): - devices.append(dev.mac + "_" + dev.conn_ap_mac) + devices.append(f"{dev.mac}_{dev.conn_ap_mac}") return devices @@ -144,7 +144,7 @@ def get_device_name(self, device): ap_name = dev.name break - return name + " on " + ap_name + return f"{name} on {ap_name}" return name diff --git a/homeassistant/components/octoprint/__init__.py b/homeassistant/components/octoprint/__init__.py index 7564330e499ade..f73e525efe3821 100644 --- a/homeassistant/components/octoprint/__init__.py +++ b/homeassistant/components/octoprint/__init__.py @@ -45,7 +45,7 @@ def ensure_valid_path(value): """Validate the path, ensuring it starts and ends with a /.""" vol.Schema(cv.string)(value) if value[0] != "/": - value = "/" + value + value = f"/{value}" if value[-1] != "/": value += "/" return value @@ -189,7 +189,7 @@ def get_tools(self): tools = [] if self.number_of_tools > 0: for tool_number in range(0, self.number_of_tools): - tools.append("tool" + str(tool_number)) + tools.append(f"tool{tool_number!s}") if self.bed: tools.append("bed") if not self.bed and self.number_of_tools == 0: @@ -231,18 +231,16 @@ def get(self, endpoint): self.printer_error_logged = False return response.json() except Exception as conn_exc: # pylint: disable=broad-except - log_string = "Failed to update OctoPrint status. " + " Error: %s" % ( - conn_exc - ) + log_string = "Failed to update OctoPrint status. Error: %s" % conn_exc # Only log the first failure if endpoint == "job": - log_string = "Endpoint: job " + log_string + log_string = f"Endpoint: job {log_string}" if not self.job_error_logged: _LOGGER.error(log_string) self.job_error_logged = True self.job_available = False elif endpoint == "printer": - log_string = "Endpoint: printer " + log_string + log_string = f"Endpoint: printer {log_string}" if not self.printer_error_logged: _LOGGER.error(log_string) self.printer_error_logged = True diff --git a/homeassistant/components/onewire/sensor.py b/homeassistant/components/onewire/sensor.py index 6405cb05adc967..936bf9f751ba7e 100644 --- a/homeassistant/components/onewire/sensor.py +++ b/homeassistant/components/onewire/sensor.py @@ -148,7 +148,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None): # We have a raw GPIO ow sensor on a Pi elif base_dir == DEFAULT_MOUNT_DIR: for device_family in DEVICE_SENSORS: - for device_folder in glob(os.path.join(base_dir, device_family + "[.-]*")): + for device_folder in glob(os.path.join(base_dir, f"{device_family}[.-]*")): sensor_id = os.path.split(device_folder)[1] device_file = os.path.join(device_folder, "w1_slave") devs.append( diff --git a/homeassistant/components/plant/__init__.py b/homeassistant/components/plant/__init__.py index cc405dcad1f643..1f440eb36dc41c 100644 --- a/homeassistant/components/plant/__init__.py +++ b/homeassistant/components/plant/__init__.py @@ -44,15 +44,15 @@ # to have a separate literal for it to avoid confusion. ATTR_DICT_OF_UNITS_OF_MEASUREMENT = "unit_of_measurement_dict" -CONF_MIN_BATTERY_LEVEL = "min_" + READING_BATTERY -CONF_MIN_TEMPERATURE = "min_" + READING_TEMPERATURE -CONF_MAX_TEMPERATURE = "max_" + READING_TEMPERATURE -CONF_MIN_MOISTURE = "min_" + READING_MOISTURE -CONF_MAX_MOISTURE = "max_" + READING_MOISTURE -CONF_MIN_CONDUCTIVITY = "min_" + READING_CONDUCTIVITY -CONF_MAX_CONDUCTIVITY = "max_" + READING_CONDUCTIVITY -CONF_MIN_BRIGHTNESS = "min_" + READING_BRIGHTNESS -CONF_MAX_BRIGHTNESS = "max_" + READING_BRIGHTNESS +CONF_MIN_BATTERY_LEVEL = f"min_{READING_BATTERY}" +CONF_MIN_TEMPERATURE = f"min_{READING_TEMPERATURE}" +CONF_MAX_TEMPERATURE = f"max_{READING_TEMPERATURE}" +CONF_MIN_MOISTURE = f"min_{READING_MOISTURE}" +CONF_MAX_MOISTURE = f"max_{READING_MOISTURE}" +CONF_MIN_CONDUCTIVITY = f"min_{READING_CONDUCTIVITY}" +CONF_MAX_CONDUCTIVITY = f"max_{READING_CONDUCTIVITY}" +CONF_MIN_BRIGHTNESS = f"min_{READING_BRIGHTNESS}" +CONF_MAX_BRIGHTNESS = f"max_{READING_BRIGHTNESS}" CONF_CHECK_DAYS = "check_days" CONF_SENSOR_BATTERY_LEVEL = READING_BATTERY diff --git a/homeassistant/components/plex/media_player.py b/homeassistant/components/plex/media_player.py index ad5fb2f73f10d1..46b797976abc95 100644 --- a/homeassistant/components/plex/media_player.py +++ b/homeassistant/components/plex/media_player.py @@ -300,7 +300,7 @@ def _set_media_type(self): elif self._session_type == "movie": self._media_content_type = MEDIA_TYPE_MOVIE if self.session.year is not None and self._media_title is not None: - self._media_title += " (" + str(self.session.year) + ")" + self._media_title += f" ({self.session.year!s})" elif self._session_type == "track": self._media_content_type = MEDIA_TYPE_MUSIC diff --git a/homeassistant/components/raspihats/__init__.py b/homeassistant/components/raspihats/__init__.py index 8b7ea0a38d75a3..fb544d3ebcc5e8 100644 --- a/homeassistant/components/raspihats/__init__.py +++ b/homeassistant/components/raspihats/__init__.py @@ -50,7 +50,7 @@ def log_message(source, *parts): """Build log message.""" message = source.__class__.__name__ for part in parts: - message += ": " + str(part) + message += f": {part!s}" return message diff --git a/homeassistant/components/raspihats/switch.py b/homeassistant/components/raspihats/switch.py index b99a84bdae97c7..8a083dbe2c9112 100644 --- a/homeassistant/components/raspihats/switch.py +++ b/homeassistant/components/raspihats/switch.py @@ -127,7 +127,7 @@ def is_on(self): state = self.I2C_HATS_MANAGER.read_dq(self._address, self._channel) return state != self._invert_logic except I2CHatsException as ex: - _LOGGER.error(self._log_message("Is ON check failed, " + str(ex))) + _LOGGER.error(self._log_message(f"Is ON check failed, {ex!s}")) return False def turn_on(self, **kwargs): @@ -137,7 +137,7 @@ def turn_on(self, **kwargs): self.I2C_HATS_MANAGER.write_dq(self._address, self._channel, state) self.schedule_update_ha_state() except I2CHatsException as ex: - _LOGGER.error(self._log_message("Turn ON failed, " + str(ex))) + _LOGGER.error(self._log_message(f"Turn ON failed, {ex!s}")) def turn_off(self, **kwargs): """Turn the device off.""" @@ -146,4 +146,4 @@ def turn_off(self, **kwargs): self.I2C_HATS_MANAGER.write_dq(self._address, self._channel, state) self.schedule_update_ha_state() except I2CHatsException as ex: - _LOGGER.error(self._log_message("Turn OFF failed:, " + str(ex))) + _LOGGER.error(self._log_message(f"Turn OFF failed, {ex!s}")) diff --git a/homeassistant/components/samsungtv/media_player.py b/homeassistant/components/samsungtv/media_player.py index 56b947ba9adbf9..fd900fedec178b 100644 --- a/homeassistant/components/samsungtv/media_player.py +++ b/homeassistant/components/samsungtv/media_player.py @@ -344,7 +344,7 @@ async def async_play_media(self, media_type, media_id, **kwargs): return for digit in media_id: - await self.hass.async_add_job(self.send_key, "KEY_" + digit) + await self.hass.async_add_job(self.send_key, f"KEY_{digit}") await asyncio.sleep(KEY_PRESS_TIMEOUT, self.hass.loop) await self.hass.async_add_job(self.send_key, "KEY_ENTER") diff --git a/homeassistant/components/sensibo/climate.py b/homeassistant/components/sensibo/climate.py index 2431b223f09ef1..08e2212e2a2168 100644 --- a/homeassistant/components/sensibo/climate.py +++ b/homeassistant/components/sensibo/climate.py @@ -65,7 +65,7 @@ "temperatureUnit", ] ) -_INITIAL_FETCH_FIELDS = "id," + _FETCH_FIELDS +_INITIAL_FETCH_FIELDS = f"id,{_FETCH_FIELDS}" FIELD_TO_FLAG = { "fanLevel": SUPPORT_FAN_MODE, diff --git a/homeassistant/components/seventeentrack/sensor.py b/homeassistant/components/seventeentrack/sensor.py index 167f4347c0cc61..43bc1b41c8f832 100644 --- a/homeassistant/components/seventeentrack/sensor.py +++ b/homeassistant/components/seventeentrack/sensor.py @@ -45,7 +45,7 @@ NOTIFICATION_DELIVERED_ID = "package_delivered_{0}" NOTIFICATION_DELIVERED_TITLE = "Package {0} delivered" NOTIFICATION_DELIVERED_MESSAGE = ( - "Package Delivered: {0}
" + "Visit 17.track for more information: " + "Package Delivered: {0}
Visit 17.track for more information: " "https://t.17track.net/track#nums={1}" ) diff --git a/homeassistant/components/sky_hub/device_tracker.py b/homeassistant/components/sky_hub/device_tracker.py index f7760a59eed596..c7dc1092b739ca 100644 --- a/homeassistant/components/sky_hub/device_tracker.py +++ b/homeassistant/components/sky_hub/device_tracker.py @@ -95,8 +95,7 @@ def _parse_skyhub_response(data_str): pattmatch = re.search("attach_dev = '(.*)'", data_str) if pattmatch is None: raise OSError( - "Error: Impossible to fetch data from" - + " Sky Hub. Try to reboot the router." + "Error: Impossible to fetch data from Sky Hub. Try to reboot the router." ) patt = pattmatch.group(1) @@ -107,8 +106,6 @@ def _parse_skyhub_response(data_str): if _MAC_REGEX.match(dvc[1]): devices[dvc[1]] = dvc[0] else: - raise RuntimeError( - "Error: MAC address " + dvc[1] + " not in correct format." - ) + raise RuntimeError(f"Error: MAC address {dvc[1]} not in correct format.") return devices diff --git a/homeassistant/components/smappee/__init__.py b/homeassistant/components/smappee/__init__.py index ecab09f6ff912e..d34653e60e7b88 100644 --- a/homeassistant/components/smappee/__init__.py +++ b/homeassistant/components/smappee/__init__.py @@ -24,7 +24,7 @@ DOMAIN = "smappee" DATA_SMAPPEE = "SMAPPEE" -_SENSOR_REGEX = re.compile(r"(?P([A-Za-z]+))\=" + r"(?P([0-9\.]+))") +_SENSOR_REGEX = re.compile(r"(?P([A-Za-z]+))\=(?P([0-9\.]+))") CONFIG_SCHEMA = vol.Schema( { diff --git a/homeassistant/components/smartthings/__init__.py b/homeassistant/components/smartthings/__init__.py index 9787fb53917c14..33f9558023db6d 100644 --- a/homeassistant/components/smartthings/__init__.py +++ b/homeassistant/components/smartthings/__init__.py @@ -279,7 +279,7 @@ def _assign_capabilities(self, devices: Iterable): capabilities = device.capabilities.copy() slots = {} for platform_name in SUPPORTED_PLATFORMS: - platform = importlib.import_module("." + platform_name, self.__module__) + platform = importlib.import_module(f".{platform_name}", self.__module__) if not hasattr(platform, "get_capabilities"): continue assigned = platform.get_capabilities(capabilities) diff --git a/homeassistant/components/smartthings/smartapp.py b/homeassistant/components/smartthings/smartapp.py index d04872909262b9..d17f6061101ad2 100644 --- a/homeassistant/components/smartthings/smartapp.py +++ b/homeassistant/components/smartthings/smartapp.py @@ -109,7 +109,7 @@ def get_webhook_url(hass: HomeAssistantType) -> str: def _get_app_template(hass: HomeAssistantType): - endpoint = "at " + hass.config.api.base_url + endpoint = f"at {hass.config.api.base_url}" cloudhook_url = hass.data[DOMAIN][CONF_CLOUDHOOK_URL] if cloudhook_url is not None: endpoint = "via Nabu Casa" diff --git a/homeassistant/components/soundtouch/media_player.py b/homeassistant/components/soundtouch/media_player.py index 4a0f6b55b227bc..72677995a9d6b3 100644 --- a/homeassistant/components/soundtouch/media_player.py +++ b/homeassistant/components/soundtouch/media_player.py @@ -304,7 +304,7 @@ def media_title(self): if self._status.station_name is not None: return self._status.station_name if self._status.artist is not None: - return self._status.artist + " - " + self._status.track + return f"{self._status.artist} - {self._status.track}" return None diff --git a/homeassistant/components/startca/sensor.py b/homeassistant/components/startca/sensor.py index 55ae15cede7ea9..e07f21e5d60486 100644 --- a/homeassistant/components/startca/sensor.py +++ b/homeassistant/components/startca/sensor.py @@ -140,7 +140,7 @@ def bytes_to_gb(value): async def async_update(self): """Get the Start.ca bandwidth data from the web service.""" _LOGGER.debug("Updating Start.ca usage data") - url = "https://www.start.ca/support/usage/api?key=" + self.api_key + url = f"https://www.start.ca/support/usage/api?key={self.api_key}" with async_timeout.timeout(REQUEST_TIMEOUT): req = await self.websession.get(url) if req.status != 200: diff --git a/homeassistant/components/tank_utility/sensor.py b/homeassistant/components/tank_utility/sensor.py index 23446257eab143..61a3d7367bfef0 100644 --- a/homeassistant/components/tank_utility/sensor.py +++ b/homeassistant/components/tank_utility/sensor.py @@ -73,7 +73,7 @@ def __init__(self, email, password, token, device): self._token = token self._device = device self._state = None - self._name = "Tank Utility " + self.device + self._name = f"Tank Utility {self.device}" self._unit_of_measurement = SENSOR_UNIT_OF_MEASUREMENT self._attributes = {} diff --git a/homeassistant/components/temper/sensor.py b/homeassistant/components/temper/sensor.py index 8b782ae4d797cc..fd26b1702dce98 100644 --- a/homeassistant/components/temper/sensor.py +++ b/homeassistant/components/temper/sensor.py @@ -39,7 +39,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None): for idx, dev in enumerate(temper_devices): if idx != 0: - name = name + "_" + str(idx) + name = f"{name}_{idx!s}" TEMPER_SENSORS.append(TemperSensor(dev, temp_unit, name, scaling)) add_entities(TEMPER_SENSORS) diff --git a/homeassistant/components/wunderground/sensor.py b/homeassistant/components/wunderground/sensor.py index 5d3bf1f74b85d7..0a566259a8802a 100644 --- a/homeassistant/components/wunderground/sensor.py +++ b/homeassistant/components/wunderground/sensor.py @@ -998,7 +998,7 @@ def __init__(self, hass: HomeAssistantType, rest, condition, unique_id_base: str self.rest.request_feature(SENSOR_TYPES[condition].feature) # This is only the suggested entity id, it might get changed by # the entity registry later. - self.entity_id = sensor.ENTITY_ID_FORMAT.format("pws_" + condition) + self.entity_id = sensor.ENTITY_ID_FORMAT.format(f"pws_{condition}") self._unique_id = f"{unique_id_base},{condition}" self._device_class = self._cfg_expand("device_class") @@ -1122,11 +1122,11 @@ def _build_url(self, baseurl=_RESOURCE): self._api_key, "/".join(sorted(self._features)), self._lang ) if self._pws_id: - url = url + f"pws:{self._pws_id}" + url = f"{url}pws:{self._pws_id}" else: - url = url + f"{self._latitude},{self._longitude}" + url = f"{url}{self._latitude},{self._longitude}" - return url + ".json" + return f"{url}.json" @Throttle(MIN_TIME_BETWEEN_UPDATES) async def async_update(self): diff --git a/homeassistant/components/x10/light.py b/homeassistant/components/x10/light.py index 1f74326d544c09..7be2f12d949b80 100644 --- a/homeassistant/components/x10/light.py +++ b/homeassistant/components/x10/light.py @@ -34,7 +34,7 @@ def x10_command(command): def get_unit_status(code): """Get on/off status for given unit.""" - output = check_output("heyu onstate " + code, shell=True) + output = check_output(f"heyu onstate {code}", shell=True) return int(output.decode("utf-8")[0]) @@ -84,18 +84,18 @@ def supported_features(self): def turn_on(self, **kwargs): """Instruct the light to turn on.""" if self._is_cm11a: - x10_command("on " + self._id) + x10_command(f"on {self._id}") else: - x10_command("fon " + self._id) + x10_command(f"fon {self._id}") self._brightness = kwargs.get(ATTR_BRIGHTNESS, 255) self._state = True def turn_off(self, **kwargs): """Instruct the light to turn off.""" if self._is_cm11a: - x10_command("off " + self._id) + x10_command(f"off {self._id}") else: - x10_command("foff " + self._id) + x10_command(f"foff {self._id}") self._state = False def update(self): diff --git a/homeassistant/components/yeelight/light.py b/homeassistant/components/yeelight/light.py index c40ead2a892375..61de12eafbfd1e 100644 --- a/homeassistant/components/yeelight/light.py +++ b/homeassistant/components/yeelight/light.py @@ -935,6 +935,6 @@ def _get_property(self, prop, default=None): bg_prop = self.PROPERTIES_MAPPING.get(prop) if not bg_prop: - bg_prop = "bg_" + prop + bg_prop = f"bg_{prop}" return super()._get_property(bg_prop, default) diff --git a/homeassistant/components/zha/api.py b/homeassistant/components/zha/api.py index 1294fcaedbd518..6228a2bc0c8a10 100644 --- a/homeassistant/components/zha/api.py +++ b/homeassistant/components/zha/api.py @@ -797,7 +797,7 @@ async def async_binding_operation(zha_gateway, source_ieee, target_ieee, operati operation.name, target_ieee, ) - zdo.debug("processing " + op_msg, *op_params) + zdo.debug(f"processing {op_msg}", *op_params) bind_tasks.append( ( diff --git a/homeassistant/components/zha/core/channels/__init__.py b/homeassistant/components/zha/core/channels/__init__.py index 5a337b2a5373f9..a5ecf21e0c38e1 100644 --- a/homeassistant/components/zha/core/channels/__init__.py +++ b/homeassistant/components/zha/core/channels/__init__.py @@ -263,7 +263,7 @@ async def get_attribute_value(self, attribute, from_cache=True): def log(self, level, msg, *args): """Log a message.""" - msg = "[%s:%s]: " + msg + msg = f"[%s:%s]: {msg}" args = (self.device.nwk, self._id,) + args _LOGGER.log(level, msg, *args) @@ -357,7 +357,7 @@ async def async_configure(self): def log(self, level, msg, *args): """Log a message.""" - msg = "[%s:ZDO](%s): " + msg + msg = f"[%s:ZDO](%s): {msg}" args = (self._zha_device.nwk, self._zha_device.model) + args _LOGGER.log(level, msg, *args) diff --git a/homeassistant/components/zha/core/device.py b/homeassistant/components/zha/core/device.py index 77e0263c06c34a..dbaf3fd44352b2 100644 --- a/homeassistant/components/zha/core/device.py +++ b/homeassistant/components/zha/core/device.py @@ -528,6 +528,6 @@ async def async_remove_from_group(self, group_id): def log(self, level, msg, *args): """Log a message.""" - msg = "[%s](%s): " + msg + msg = f"[%s](%s): {msg}" args = (self.nwk, self.model) + args _LOGGER.log(level, msg, *args) diff --git a/homeassistant/components/zha/entity.py b/homeassistant/components/zha/entity.py index 102472d25b0cbc..0b001bdedbc7bf 100644 --- a/homeassistant/components/zha/entity.py +++ b/homeassistant/components/zha/entity.py @@ -185,6 +185,6 @@ async def async_accept_signal(self, channel, signal, func, signal_override=False def log(self, level, msg, *args): """Log a message.""" - msg = "%s: " + msg + msg = f"%s: {msg}" args = (self.entity_id,) + args _LOGGER.log(level, msg, *args) diff --git a/homeassistant/components/zhong_hong/climate.py b/homeassistant/components/zhong_hong/climate.py index b94e19d6dbdb10..203131afdb1d28 100644 --- a/homeassistant/components/zhong_hong/climate.py +++ b/homeassistant/components/zhong_hong/climate.py @@ -161,9 +161,7 @@ def name(self): @property def unique_id(self): """Return the unique ID of the HVAC.""" - return "zhong_hong_hvac_{}_{}".format( - self._device.addr_out, self._device.addr_in - ) + return f"zhong_hong_hvac_{self._device.addr_out}_{self._device.addr_in}" @property def supported_features(self): diff --git a/homeassistant/components/zwave/cover.py b/homeassistant/components/zwave/cover.py index 5b4fb0c9934a2a..724977a4220186 100644 --- a/homeassistant/components/zwave/cover.py +++ b/homeassistant/components/zwave/cover.py @@ -37,7 +37,7 @@ def _to_hex_str(id_in_bytes): Example: 0x1234 --> '0x1234' """ - return "0x{:04x}".format(id_in_bytes) + return f"0x{id_in_bytes:04x}" # For some reason node.manufacturer_id is of type string. So we need to convert diff --git a/homeassistant/config.py b/homeassistant/config.py index ee3ccc15f81935..6777c1ef5a570d 100644 --- a/homeassistant/config.py +++ b/homeassistant/config.py @@ -572,9 +572,7 @@ async def async_process_ha_core_config(hass: HomeAssistant, config: Dict) -> Non def _log_pkg_error(package: str, component: str, config: Dict, message: str) -> None: """Log an error while merging packages.""" - message = "Package {} setup failed. Integration {} {}".format( - package, component, message - ) + message = f"Package {package} setup failed. Integration {component} {message}" pack_config = config[CONF_CORE][CONF_PACKAGES].get(package, config) message += " (See {}:{}). ".format( diff --git a/homeassistant/const.py b/homeassistant/const.py index 15dc5a099bc0ab..ae055c52f10249 100644 --- a/homeassistant/const.py +++ b/homeassistant/const.py @@ -2,8 +2,8 @@ MAJOR_VERSION = 0 MINOR_VERSION = 104 PATCH_VERSION = "0.dev0" -__short_version__ = "{}.{}".format(MAJOR_VERSION, MINOR_VERSION) -__version__ = "{}.{}".format(__short_version__, PATCH_VERSION) +__short_version__ = f"{MAJOR_VERSION}.{MINOR_VERSION}" +__version__ = f"{__short_version__}.{PATCH_VERSION}" REQUIRED_PYTHON_VER = (3, 7, 0) # Truthy date string triggers showing related deprecation warning messages. REQUIRED_NEXT_PYTHON_VER = (3, 8, 0) diff --git a/homeassistant/core.py b/homeassistant/core.py index e76673f572734e..af27110dc9d863 100644 --- a/homeassistant/core.py +++ b/homeassistant/core.py @@ -712,18 +712,14 @@ def __init__( if not valid_entity_id(entity_id) and not temp_invalid_id_bypass: raise InvalidEntityFormatError( - ( - "Invalid entity id encountered: {}. " - "Format should be ." - ).format(entity_id) + f"Invalid entity id encountered: {entity_id}. " + "Format should be ." ) if not valid_state(state): raise InvalidStateError( - ( - "Invalid state encountered for entity id: {}. " - "State max length is 255 characters." - ).format(entity_id) + f"Invalid state encountered for entity id: {entity_id}. " + "State max length is 255 characters." ) self.entity_id = entity_id.lower() @@ -1034,9 +1030,7 @@ def __repr__(self) -> str: self.domain, self.service, self.context.id, util.repr_helper(self.data) ) - return "".format( - self.domain, self.service, self.context.id - ) + return f"" class ServiceRegistry: diff --git a/homeassistant/data_entry_flow.py b/homeassistant/data_entry_flow.py index 6a9f5b1dc5a78f..5e72dea9273ae2 100644 --- a/homeassistant/data_entry_flow.py +++ b/homeassistant/data_entry_flow.py @@ -153,9 +153,7 @@ async def _async_handle_step( if not hasattr(flow, method): self._progress.pop(flow.flow_id) raise UnknownStep( - "Handler {} doesn't support step {}".format( - flow.__class__.__name__, step_id - ) + f"Handler {flow.__class__.__name__} doesn't support step {step_id}" ) try: diff --git a/homeassistant/helpers/__init__.py b/homeassistant/helpers/__init__.py index 125d90e1162b96..ad97456968b864 100644 --- a/homeassistant/helpers/__init__.py +++ b/homeassistant/helpers/__init__.py @@ -36,5 +36,5 @@ def extract_domain_configs(config: ConfigType, domain: str) -> Sequence[str]: Async friendly. """ - pattern = re.compile(r"^{}(| .+)$".format(domain)) + pattern = re.compile(fr"^{domain}(| .+)$") return [key for key in config.keys() if pattern.match(key)] diff --git a/homeassistant/helpers/check_config.py b/homeassistant/helpers/check_config.py index 1b1e136ed894b3..6ac1326545a5ce 100644 --- a/homeassistant/helpers/check_config.py +++ b/homeassistant/helpers/check_config.py @@ -69,9 +69,7 @@ def _pack_error( package: str, component: str, config: ConfigType, message: str ) -> None: """Handle errors from packages: _log_pkg_error.""" - message = "Package {} setup failed. Component {} {}".format( - package, component, message - ) + message = f"Package {package} setup failed. Component {component} {message}" domain = f"homeassistant.packages.{package}.{component}" pack_config = core_config[CONF_PACKAGES].get(package, config) result.add_error(message, domain, pack_config) diff --git a/homeassistant/helpers/config_validation.py b/homeassistant/helpers/config_validation.py index bcf0d42df70841..e357a2ba622cfb 100644 --- a/homeassistant/helpers/config_validation.py +++ b/homeassistant/helpers/config_validation.py @@ -135,7 +135,7 @@ def boolean(value: Any) -> bool: elif isinstance(value, Number): # type ignore: https://github.com/python/mypy/issues/3186 return value != 0 # type: ignore - raise vol.Invalid("invalid boolean value {}".format(value)) + raise vol.Invalid(f"invalid boolean value {value}") def isdevice(value: Any) -> str: @@ -144,7 +144,7 @@ def isdevice(value: Any) -> str: os.stat(value) return str(value) except OSError: - raise vol.Invalid("No device at {} found".format(value)) + raise vol.Invalid(f"No device at {value} found") def matches_regex(regex: str) -> Callable[[Any], str]: @@ -154,13 +154,11 @@ def matches_regex(regex: str) -> Callable[[Any], str]: def validator(value: Any) -> str: """Validate that value matches the given regex.""" if not isinstance(value, str): - raise vol.Invalid("not a string value: {}".format(value)) + raise vol.Invalid(f"not a string value: {value}") if not compiled.match(value): raise vol.Invalid( - "value {} does not match regular expression {}".format( - value, compiled.pattern - ) + f"value {value} does not match regular expression {compiled.pattern}" ) return value @@ -175,10 +173,10 @@ def is_regex(value: Any) -> Pattern[Any]: return r except TypeError: raise vol.Invalid( - "value {} is of the wrong type for a regular expression".format(value) + f"value {value} is of the wrong type for a regular expression" ) except re.error: - raise vol.Invalid("value {} is not a valid regular expression".format(value)) + raise vol.Invalid(f"value {value} is not a valid regular expression") def isfile(value: Any) -> str: @@ -220,7 +218,7 @@ def entity_id(value: Any) -> str: if valid_entity_id(str_value): return str_value - raise vol.Invalid("Entity ID {} is an invalid entity id".format(value)) + raise vol.Invalid(f"Entity ID {value} is an invalid entity id") def entity_ids(value: Union[str, List]) -> List[str]: @@ -256,9 +254,7 @@ def validate(values: Union[str, List]) -> List[str]: for ent_id in values: if split_entity_id(ent_id)[0] != domain: raise vol.Invalid( - "Entity ID '{}' does not belong to domain '{}'".format( - ent_id, domain - ) + f"Entity ID '{ent_id}' does not belong to domain '{domain}'" ) return values @@ -307,7 +303,7 @@ def time(value: Any) -> time_sys: raise vol.Invalid("Not a parseable type") if time_val is None: - raise vol.Invalid("Invalid time specified: {}".format(value)) + raise vol.Invalid(f"Invalid time specified: {value}") return time_val @@ -368,7 +364,7 @@ def time_period_seconds(value: Union[int, str]) -> timedelta: try: return timedelta(seconds=int(value)) except (ValueError, TypeError): - raise vol.Invalid("Expected seconds, got {}".format(value)) + raise vol.Invalid(f"Expected seconds, got {value}") time_period = vol.Any(time_period_str, time_period_seconds, timedelta, time_period_dict) @@ -400,7 +396,7 @@ def service(value: Any) -> str: str_value = string(value).lower() if valid_entity_id(str_value): return str_value - raise vol.Invalid("Service {} does not match format .".format(value)) + raise vol.Invalid(f"Service {value} does not match format .") def schema_with_slug_keys(value_schema: Union[T, Callable]) -> Callable: @@ -432,7 +428,7 @@ def slug(value: Any) -> str: slg = util_slugify(str_value) if str_value == slg: return str_value - raise vol.Invalid("invalid slug {} (try {})".format(value, slg)) + raise vol.Invalid(f"invalid slug {value} (try {slg})") def slugify(value: Any) -> str: @@ -442,7 +438,7 @@ def slugify(value: Any) -> str: slg = util_slugify(str(value)) if slg: return slg - raise vol.Invalid("Unable to slugify {}".format(value)) + raise vol.Invalid(f"Unable to slugify {value}") def string(value: Any) -> str: @@ -484,7 +480,7 @@ def template(value: Optional[Any]) -> template_helper.Template: template_value.ensure_valid() return cast(template_helper.Template, template_value) except TemplateError as ex: - raise vol.Invalid("invalid template ({})".format(ex)) + raise vol.Invalid(f"invalid template ({ex})") def template_complex(value: Any) -> Any: @@ -515,7 +511,7 @@ def datetime(value: Any) -> datetime_sys: date_val = None if date_val is None: - raise vol.Invalid("Invalid datetime specified: {}".format(value)) + raise vol.Invalid(f"Invalid datetime specified: {value}") return date_val @@ -545,8 +541,8 @@ def socket_timeout(value: Optional[Any]) -> object: if float_value > 0.0: return float_value raise vol.Invalid("Invalid socket timeout value. float > 0.0 required.") - except Exception as _: - raise vol.Invalid("Invalid socket timeout: {err}".format(err=_)) + except Exception as err: + raise vol.Invalid(f"Invalid socket timeout: {err}") # pylint: disable=no-value-for-parameter @@ -700,8 +696,8 @@ def validator(value: Dict[Hashable, Any]) -> Dict[Hashable, Any]: raise vol.Invalid("key dependencies require a dict") if key in value and dependency not in value: raise vol.Invalid( - 'dependency violation - key "{}" requires ' - 'key "{}" to exist'.format(key, dependency) + f'dependency violation - key "{key}" requires ' + f'key "{dependency}" to exist' ) return value diff --git a/homeassistant/helpers/discovery.py b/homeassistant/helpers/discovery.py index a6162dbde557f7..806540e57cef3a 100644 --- a/homeassistant/helpers/discovery.py +++ b/homeassistant/helpers/discovery.py @@ -65,7 +65,7 @@ def discover(hass, service, discovered, component, hass_config): async def async_discover(hass, service, discovered, component, hass_config): """Fire discovery event. Can ensure a component is loaded.""" if component in DEPENDENCY_BLACKLIST: - raise HomeAssistantError("Cannot discover the {} component.".format(component)) + raise HomeAssistantError(f"Cannot discover the {component} component.") if component is not None and component not in hass.config.components: await setup.async_setup_component(hass, component, hass_config) @@ -151,7 +151,7 @@ async def async_load_platform(hass, component, platform, discovered, hass_config assert hass_config, "You need to pass in the real hass config" if component in DEPENDENCY_BLACKLIST: - raise HomeAssistantError("Cannot discover the {} component.".format(component)) + raise HomeAssistantError(f"Cannot discover the {component} component.") setup_success = True diff --git a/homeassistant/helpers/entity.py b/homeassistant/helpers/entity.py index b1786130b582be..b7c806950a015f 100644 --- a/homeassistant/helpers/entity.py +++ b/homeassistant/helpers/entity.py @@ -562,7 +562,7 @@ def __eq__(self, other): def __repr__(self) -> str: """Return the representation.""" - return "".format(self.name, self.state) + return f"" # call an requests async def async_request_call(self, coro): diff --git a/homeassistant/helpers/entity_platform.py b/homeassistant/helpers/entity_platform.py index 9b82eb76dec520..82236875ea4d10 100644 --- a/homeassistant/helpers/entity_platform.py +++ b/homeassistant/helpers/entity_platform.py @@ -304,9 +304,7 @@ async def _async_add_entity( suggested_object_id = entity.name if self.entity_namespace is not None: - suggested_object_id = "{} {}".format( - self.entity_namespace, suggested_object_id - ) + suggested_object_id = f"{self.entity_namespace} {suggested_object_id}" if self.config_entry is not None: config_entry_id = self.config_entry.entry_id @@ -380,9 +378,7 @@ async def _async_add_entity( ) if self.entity_namespace is not None: - suggested_object_id = "{} {}".format( - self.entity_namespace, suggested_object_id - ) + suggested_object_id = f"{self.entity_namespace} {suggested_object_id}" entity.entity_id = entity_registry.async_generate_entity_id( self.domain, suggested_object_id, self.entities.keys() ) @@ -402,9 +398,7 @@ async def _async_add_entity( if already_exists: msg = f"Entity id already exists: {entity.entity_id}" if entity.unique_id is not None: - msg += ". Platform {} does not generate unique IDs".format( - self.platform_name - ) + msg += f". Platform {self.platform_name} does not generate unique IDs" raise HomeAssistantError(msg) entity_id = entity.entity_id diff --git a/homeassistant/helpers/entity_registry.py b/homeassistant/helpers/entity_registry.py index 77d8ccc00e08e5..2673162a841fdd 100644 --- a/homeassistant/helpers/entity_registry.py +++ b/homeassistant/helpers/entity_registry.py @@ -323,9 +323,8 @@ def _async_update_entity( ) if conflict: raise ValueError( - "Unique id '{}' is already in use by '{}'".format( - new_unique_id, conflict.entity_id - ) + f"Unique id '{new_unique_id}' is already in use by " + f"'{conflict.entity_id}'" ) changes["unique_id"] = new_unique_id diff --git a/homeassistant/helpers/icon.py b/homeassistant/helpers/icon.py index b2a1d58717bce2..dd64e9c92f11d6 100644 --- a/homeassistant/helpers/icon.py +++ b/homeassistant/helpers/icon.py @@ -8,7 +8,7 @@ def icon_for_battery_level( """Return a battery icon valid identifier.""" icon = "mdi:battery" if battery_level is None: - return icon + "-unknown" + return f"{icon}-unknown" if charging and battery_level > 10: icon += "-charging-{}".format(int(round(battery_level / 20 - 0.01)) * 20) elif charging: diff --git a/homeassistant/helpers/intent.py b/homeassistant/helpers/intent.py index 181d1baebc0b09..8fdf617e3f6547 100644 --- a/homeassistant/helpers/intent.py +++ b/homeassistant/helpers/intent.py @@ -158,7 +158,7 @@ async def async_handle(self, intent_obj: "Intent") -> "IntentResponse": def __repr__(self) -> str: """Represent a string of an intent handler.""" - return "<{} - {}>".format(self.__class__.__name__, self.intent_type) + return f"<{self.__class__.__name__} - {self.intent_type}>" def _fuzzymatch(name: str, items: Iterable[T], key: Callable[[T], str]) -> Optional[T]: diff --git a/homeassistant/helpers/script.py b/homeassistant/helpers/script.py index 8e0faa2ce4d1a7..837a561181d407 100644 --- a/homeassistant/helpers/script.py +++ b/homeassistant/helpers/script.py @@ -299,7 +299,7 @@ def async_script_delay(now): _LOGGER.error("Error rendering '%s' delay template: %s", self.name, ex) raise _StopScript - self.last_action = action.get(CONF_ALIAS, "delay {}".format(delay)) + self.last_action = action.get(CONF_ALIAS, f"delay {delay}") self._log("Executing step %s" % self.last_action) unsub = async_track_point_in_utc_time( @@ -408,7 +408,7 @@ async def _async_check_condition(self, action, variables, context): self.last_action = action.get(CONF_ALIAS, action[CONF_CONDITION]) check = config(self.hass, variables) - self._log("Test condition {}: {}".format(self.last_action, check)) + self._log(f"Test condition {self.last_action}: {check}") if not check: raise _StopScript @@ -446,6 +446,6 @@ def _async_remove_listener(self): def _log(self, msg): """Logger helper.""" if self.name is not None: - msg = "Script {}: {}".format(self.name, msg) + msg = f"Script {self.name}: {msg}" _LOGGER.info(msg) diff --git a/homeassistant/helpers/service.py b/homeassistant/helpers/service.py index 5381f7659934f4..16fabe251afbe1 100644 --- a/homeassistant/helpers/service.py +++ b/homeassistant/helpers/service.py @@ -240,7 +240,7 @@ def async_set_service_schema(hass, domain, service, schema): "fields": schema.get("fields") or {}, } - hass.data[SERVICE_DESCRIPTION_CACHE]["{}.{}".format(domain, service)] = description + hass.data[SERVICE_DESCRIPTION_CACHE][f"{domain}.{service}"] = description @bind_hass diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index b27120e1825f39..8565315f87f5c9 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -328,7 +328,7 @@ def __getattr__(self, name): if not valid_entity_id(name): raise TemplateError(f"Invalid entity ID '{name}'") return _get_state(self._hass, name) - if not valid_entity_id(name + ".entity"): + if not valid_entity_id(f"{name}.entity"): raise TemplateError(f"Invalid domain name '{name}'") return DomainStates(self._hass, name) @@ -451,7 +451,7 @@ def __repr__(self): """Representation of Template State.""" state = object.__getattribute__(self, "_access_state")() rep = state.__repr__() - return "