From b2af1de27338adc6dca49b0e8c5f98957947d0f2 Mon Sep 17 00:00:00 2001 From: springstan <46536646+springstan@users.noreply.github.com> Date: Sun, 12 Apr 2020 17:18:09 +0200 Subject: [PATCH] Improve string formatting v9 (#34050) * Improve string formatting v9 * Address review comments --- homeassistant/auth/mfa_modules/totp.py | 2 +- .../components/osramlightify/light.py | 7 ++---- .../components/owntracks/messages.py | 4 ++-- homeassistant/components/pi_hole/__init__.py | 17 ++++++-------- homeassistant/components/plaato/__init__.py | 2 +- homeassistant/components/point/__init__.py | 2 +- homeassistant/components/prowl/notify.py | 2 +- .../components/proximity/__init__.py | 2 +- homeassistant/components/proxy/camera.py | 6 ++--- homeassistant/components/ps4/__init__.py | 6 ++--- homeassistant/components/ps4/media_player.py | 2 +- homeassistant/components/pushbullet/sensor.py | 2 +- homeassistant/components/pyload/sensor.py | 8 +++---- homeassistant/components/qnap/sensor.py | 10 +++----- .../components/qrcode/image_processing.py | 2 +- .../components/qwikswitch/__init__.py | 4 +--- homeassistant/components/radarr/sensor.py | 2 +- .../components/raincloud/__init__.py | 6 ++--- .../components/rainmachine/__init__.py | 6 ++--- homeassistant/core.py | 23 ++++++++----------- homeassistant/loader.py | 4 +--- 21 files changed, 47 insertions(+), 72 deletions(-) diff --git a/homeassistant/auth/mfa_modules/totp.py b/homeassistant/auth/mfa_modules/totp.py index 142bf32baba..d35f237f424 100644 --- a/homeassistant/auth/mfa_modules/totp.py +++ b/homeassistant/auth/mfa_modules/totp.py @@ -41,7 +41,7 @@ def _generate_qr_code(data: str) -> str: with BytesIO() as buffer: qr_code.svg(file=buffer, scale=4) - return "{}".format( + return str( buffer.getvalue() .decode("ascii") .replace("\n", "") diff --git a/homeassistant/components/osramlightify/light.py b/homeassistant/components/osramlightify/light.py index 5cb9c481c3a..ed79604a3f8 100644 --- a/homeassistant/components/osramlightify/light.py +++ b/homeassistant/components/osramlightify/light.py @@ -74,8 +74,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None): try: bridge = Lightify(host, log_level=logging.NOTSET) except OSError as err: - msg = "Error connecting to bridge: {} due to: {}".format(host, str(err)) - _LOGGER.exception(msg) + _LOGGER.exception("Error connecting to bridge: %s due to: %s", host, err) return setup_bridge(bridge, add_entities, config) @@ -380,9 +379,7 @@ class OsramLightifyLight(Luminary): """Update static attributes of the luminary.""" super().update_static_attributes() attrs = { - "device_type": "{} ({})".format( - self._luminary.type_id(), self._luminary.devicename() - ), + "device_type": f"{self._luminary.type_id()} ({self._luminary.devicename()})", "firmware_version": self._luminary.version(), } if self._luminary.devicetype().name == "SENSOR": diff --git a/homeassistant/components/owntracks/messages.py b/homeassistant/components/owntracks/messages.py index 8814c8968a0..4d5995c558b 100644 --- a/homeassistant/components/owntracks/messages.py +++ b/homeassistant/components/owntracks/messages.py @@ -199,7 +199,7 @@ async def async_handle_location_message(hass, context, message): async def _async_transition_message_enter(hass, context, message, location): """Execute enter event.""" - zone = hass.states.get("zone.{}".format(slugify(location))) + zone = hass.states.get(f"zone.{slugify(location)}") dev_id, kwargs = _parse_see_args(message, context.mqtt_topic) if zone is None and message.get("t") == "b": @@ -240,7 +240,7 @@ async def _async_transition_message_leave(hass, context, message, location): new_region = regions[-1] if regions else None if new_region: # Exit to previous region - zone = hass.states.get("zone.{}".format(slugify(new_region))) + zone = hass.states.get(f"zone.{slugify(new_region)}") _set_gps_from_zone(kwargs, new_region, zone) _LOGGER.info("Exit to %s", new_region) context.async_see(**kwargs) diff --git a/homeassistant/components/pi_hole/__init__.py b/homeassistant/components/pi_hole/__init__.py index fb06d06cfb4..989841d1317 100644 --- a/homeassistant/components/pi_hole/__init__.py +++ b/homeassistant/components/pi_hole/__init__.py @@ -45,12 +45,10 @@ def ensure_unique_names_and_slugs(config): slugs[conf[CONF_SLUG]] = conf[CONF_HOST] else: raise vol.Invalid( - "Duplicate name '{}' (or slug '{}') for '{}' (already in use by '{}'). Each configured Pi-hole must have a unique name.".format( - conf[CONF_NAME], - conf[CONF_SLUG], - conf[CONF_HOST], - names.get(conf[CONF_NAME], slugs[conf[CONF_SLUG]]), - ) + f"Duplicate name '{conf[CONF_NAME]}' (or slug '{conf[CONF_SLUG]}') " + f"for '{conf[CONF_HOST]}' (already in use by " + f"'{names.get(conf[CONF_NAME], slugs[conf[CONF_SLUG]])}'). " + "Each configured Pi-hole must have a unique name." ) return config @@ -108,9 +106,8 @@ async def async_setup(hass, config): if (data[slug]).api.api_token is None: raise vol.Invalid( - "Pi-hole '{}' must have an api_key provided in configuration to be enabled.".format( - pi_hole.name - ) + f"Pi-hole '{pi_hole.name}' must have an api_key " + "provided in configuration to be enabled." ) return call_data @@ -122,7 +119,7 @@ async def async_setup(hass, config): cv.time_period_str, cv.positive_timedelta ), vol.Optional(SERVICE_DISABLE_ATTR_NAME): vol.In( - [conf[CONF_NAME] for conf in config[DOMAIN]], msg="Unknown Pi-Hole", + [conf[CONF_NAME] for conf in config[DOMAIN]], msg="Unknown Pi-Hole" ), }, ensure_api_token, diff --git a/homeassistant/components/plaato/__init__.py b/homeassistant/components/plaato/__init__.py index 0dd57f75812..b365c7e0081 100644 --- a/homeassistant/components/plaato/__init__.py +++ b/homeassistant/components/plaato/__init__.py @@ -127,4 +127,4 @@ async def handle_webhook(hass, webhook_id, request): def _device_id(data): """Return name of device sensor.""" - return "{}_{}".format(data.get(ATTR_DEVICE_NAME), data.get(ATTR_DEVICE_ID)) + return f"{data.get(ATTR_DEVICE_NAME)}_{data.get(ATTR_DEVICE_ID)}" diff --git a/homeassistant/components/point/__init__.py b/homeassistant/components/point/__init__.py index d2e4826ba2d..2d6f39feb11 100644 --- a/homeassistant/components/point/__init__.py +++ b/homeassistant/components/point/__init__.py @@ -309,7 +309,7 @@ class MinutPointEntity(Entity): "connections": {("mac", device["device_mac"])}, "identifieres": device["device_id"], "manufacturer": "Minut", - "model": "Point v{}".format(device["hardware_version"]), + "model": f"Point v{device['hardware_version']}", "name": device["description"], "sw_version": device["firmware"]["installed"], "via_device": (DOMAIN, device["home"]), diff --git a/homeassistant/components/prowl/notify.py b/homeassistant/components/prowl/notify.py index ada7fbb5f34..5d2efe76607 100644 --- a/homeassistant/components/prowl/notify.py +++ b/homeassistant/components/prowl/notify.py @@ -39,7 +39,7 @@ class ProwlNotificationService(BaseNotificationService): """Send the message to the user.""" response = None session = None - url = "{}{}".format(_RESOURCE, "add") + url = f"{_RESOURCE}add" data = kwargs.get(ATTR_DATA) payload = { "apikey": self._api_key, diff --git a/homeassistant/components/proximity/__init__.py b/homeassistant/components/proximity/__init__.py index 3509b1ba8e1..c82818bca1a 100644 --- a/homeassistant/components/proximity/__init__.py +++ b/homeassistant/components/proximity/__init__.py @@ -61,7 +61,7 @@ def setup_proximity_component(hass, name, config): unit_of_measurement = config.get( CONF_UNIT_OF_MEASUREMENT, hass.config.units.length_unit ) - zone_id = "zone.{}".format(config.get(CONF_ZONE)) + zone_id = f"zone.{config.get(CONF_ZONE)}" proximity = Proximity( hass, diff --git a/homeassistant/components/proxy/camera.py b/homeassistant/components/proxy/camera.py index a2912ef0dbe..7aa83d30ae4 100644 --- a/homeassistant/components/proxy/camera.py +++ b/homeassistant/components/proxy/camera.py @@ -188,8 +188,8 @@ class ProxyCamera(Camera): super().__init__() self.hass = hass self._proxied_camera = config.get(CONF_ENTITY_ID) - self._name = config.get(CONF_NAME) or "{} - {}".format( - DEFAULT_BASENAME, self._proxied_camera + self._name = ( + config.get(CONF_NAME) or f"{DEFAULT_BASENAME} - {self._proxied_camera}" ) self._image_opts = ImageOpts( config.get(CONF_MAX_IMAGE_WIDTH), @@ -258,7 +258,7 @@ class ProxyCamera(Camera): ) return await async_get_still_stream( - request, self._async_stream_image, self.content_type, self.frame_interval, + request, self._async_stream_image, self.content_type, self.frame_interval ) @property diff --git a/homeassistant/components/ps4/__init__.py b/homeassistant/components/ps4/__init__.py index 05e3422fe74..d2c6e9859de 100644 --- a/homeassistant/components/ps4/__init__.py +++ b/homeassistant/components/ps4/__init__.py @@ -139,11 +139,9 @@ async def async_migrate_entry(hass, entry): config_entries.async_update_entry(entry) return True - msg = """{} for the PlayStation 4 Integration. + msg = f"""{reason[version]} for the PlayStation 4 Integration. Please remove the PS4 Integration and re-configure - [here](/config/integrations).""".format( - reason[version] - ) + [here](/config/integrations).""" hass.components.persistent_notification.async_create( title="PlayStation 4 Integration Configuration Requires Update", diff --git a/homeassistant/components/ps4/media_player.py b/homeassistant/components/ps4/media_player.py index 3aa65734d34..3acaf75d699 100644 --- a/homeassistant/components/ps4/media_player.py +++ b/homeassistant/components/ps4/media_player.py @@ -352,7 +352,7 @@ class PS4Device(MediaPlayerDevice): else: _sw_version = status["system-version"] _sw_version = _sw_version[1:4] - sw_version = "{}.{}".format(_sw_version[0], _sw_version[1:]) + sw_version = f"{_sw_version[0]}.{_sw_version[1:]}" self._info = { "name": status["host-name"], "model": "PlayStation 4", diff --git a/homeassistant/components/pushbullet/sensor.py b/homeassistant/components/pushbullet/sensor.py index 771ba55586c..ff18e86aad9 100644 --- a/homeassistant/components/pushbullet/sensor.py +++ b/homeassistant/components/pushbullet/sensor.py @@ -77,7 +77,7 @@ class PushBulletNotificationSensor(Entity): @property def name(self): """Return the name of the sensor.""" - return "{} {}".format("Pushbullet", self._element) + return f"Pushbullet {self._element}" @property def state(self): diff --git a/homeassistant/components/pyload/sensor.py b/homeassistant/components/pyload/sensor.py index 249fb85bacc..abcf1193ce4 100644 --- a/homeassistant/components/pyload/sensor.py +++ b/homeassistant/components/pyload/sensor.py @@ -83,7 +83,7 @@ class PyLoadSensor(Entity): def __init__(self, api, sensor_type, client_name): """Initialize a new pyLoad sensor.""" - self._name = "{} {}".format(client_name, sensor_type[1]) + self._name = f"{client_name} {sensor_type[1]}" self.type = sensor_type[0] self.api = api self._state = None @@ -141,9 +141,7 @@ class PyLoadAPI: if username is not None and password is not None: self.payload = {"username": username, "password": password} - self.login = requests.post( - "{}{}".format(api_url, "login"), data=self.payload, timeout=5 - ) + self.login = requests.post(f"{api_url}login", data=self.payload, timeout=5) self.update() def post(self, method, params=None): @@ -155,7 +153,7 @@ class PyLoadAPI: try: response = requests.post( - "{}{}".format(self.api_url, "statusServer"), + f"{self.api_url}statusServer", json=payload, cookies=self.login.cookies, headers=self.headers, diff --git a/homeassistant/components/qnap/sensor.py b/homeassistant/components/qnap/sensor.py index dc148d4f516..aefbe760d6a 100644 --- a/homeassistant/components/qnap/sensor.py +++ b/homeassistant/components/qnap/sensor.py @@ -177,7 +177,7 @@ class QNAPStatsAPI: protocol = "https" if config[CONF_SSL] else "http" self._api = QNAPStats( - "{}://{}".format(protocol, config.get(CONF_HOST)), + f"{protocol}://{config.get(CONF_HOST)}", config.get(CONF_PORT), config.get(CONF_USERNAME), config.get(CONF_PASSWORD), @@ -357,9 +357,7 @@ class QNAPDriveSensor(QNAPSensor): """Return the name of the sensor, if any.""" server_name = self._api.data["system_stats"]["system"]["name"] - return "{} {} (Drive {})".format( - server_name, self.var_name, self.monitor_device - ) + return f"{server_name} {self.var_name} (Drive {self.monitor_device})" @property def device_state_attributes(self): @@ -402,6 +400,4 @@ class QNAPVolumeSensor(QNAPSensor): data = self._api.data["volumes"][self.monitor_device] total_gb = int(data["total_size"]) / 1024 / 1024 / 1024 - return { - ATTR_VOLUME_SIZE: "{} {}".format(round_nicely(total_gb), DATA_GIBIBYTES) - } + return {ATTR_VOLUME_SIZE: f"{round_nicely(total_gb)} {DATA_GIBIBYTES}"} diff --git a/homeassistant/components/qrcode/image_processing.py b/homeassistant/components/qrcode/image_processing.py index 71bb67f0753..82f6a35ac8f 100644 --- a/homeassistant/components/qrcode/image_processing.py +++ b/homeassistant/components/qrcode/image_processing.py @@ -34,7 +34,7 @@ class QrEntity(ImageProcessingEntity): if name: self._name = name else: - self._name = "QR {}".format(split_entity_id(camera_entity)[1]) + self._name = f"QR {split_entity_id(camera_entity)[1]}" self._state = None @property diff --git a/homeassistant/components/qwikswitch/__init__.py b/homeassistant/components/qwikswitch/__init__.py index 6ad030078b1..ffe87797358 100644 --- a/homeassistant/components/qwikswitch/__init__.py +++ b/homeassistant/components/qwikswitch/__init__.py @@ -205,9 +205,7 @@ async def async_setup(hass, config): # If button pressed, fire a hass event if QS_ID in qspacket: if qspacket.get(QS_CMD, "") in cmd_buttons: - hass.bus.async_fire( - "qwikswitch.button.{}".format(qspacket[QS_ID]), qspacket - ) + hass.bus.async_fire(f"qwikswitch.button.{qspacket[QS_ID]}", qspacket) return if qspacket[QS_ID] in sensor_ids: diff --git a/homeassistant/components/radarr/sensor.py b/homeassistant/components/radarr/sensor.py index a15f8b4fe4e..27365271014 100644 --- a/homeassistant/components/radarr/sensor.py +++ b/homeassistant/components/radarr/sensor.py @@ -106,7 +106,7 @@ class RadarrSensor(Entity): self.port = conf.get(CONF_PORT) self.urlbase = conf.get(CONF_URLBASE) if self.urlbase: - self.urlbase = "{}/".format(self.urlbase.strip("/")) + self.urlbase = f"{self.urlbase.strip('/')}/" self.apikey = conf.get(CONF_API_KEY) self.included = conf.get(CONF_INCLUDED) self.days = int(conf.get(CONF_DAYS)) diff --git a/homeassistant/components/raincloud/__init__.py b/homeassistant/components/raincloud/__init__.py index cc42bdc54b8..17faea4495f 100644 --- a/homeassistant/components/raincloud/__init__.py +++ b/homeassistant/components/raincloud/__init__.py @@ -107,9 +107,7 @@ def setup(hass, config): except (ConnectTimeout, HTTPError) as ex: _LOGGER.error("Unable to connect to Rain Cloud service: %s", str(ex)) hass.components.persistent_notification.create( - "Error: {}
" - "You will need to restart hass after fixing." - "".format(ex), + f"Error: {ex}
" "You will need to restart hass after fixing.", title=NOTIFICATION_TITLE, notification_id=NOTIFICATION_ID, ) @@ -142,7 +140,7 @@ class RainCloudEntity(Entity): """Initialize the RainCloud entity.""" self.data = data self._sensor_type = sensor_type - self._name = "{} {}".format(self.data.name, KEY_MAP.get(self._sensor_type)) + self._name = f"{self.data.name} {KEY_MAP.get(self._sensor_type)}" self._state = None @property diff --git a/homeassistant/components/rainmachine/__init__.py b/homeassistant/components/rainmachine/__init__.py index e1054f296d0..2e32d0ed43d 100644 --- a/homeassistant/components/rainmachine/__init__.py +++ b/homeassistant/components/rainmachine/__init__.py @@ -425,9 +425,9 @@ class RainMachineEntity(Entity): "identifiers": {(DOMAIN, self.rainmachine.controller.mac)}, "name": self.rainmachine.controller.name, "manufacturer": "RainMachine", - "model": "Version {} (API: {})".format( - self.rainmachine.controller.hardware_version, - self.rainmachine.controller.api_version, + "model": ( + f"Version {self.rainmachine.controller.hardware_version} " + f"(API: {self.rainmachine.controller.api_version})" ), "sw_version": self.rainmachine.controller.software_version, } diff --git a/homeassistant/core.py b/homeassistant/core.py index 7e85e7616a8..8ad8c24bd53 100644 --- a/homeassistant/core.py +++ b/homeassistant/core.py @@ -509,11 +509,9 @@ class Event: """Return the representation.""" # pylint: disable=maybe-no-member if self.data: - return "".format( - self.event_type, str(self.origin)[0], util.repr_helper(self.data) - ) + return f"" - return "".format(self.event_type, str(self.origin)[0]) + return f"" def __eq__(self, other: Any) -> bool: """Return the comparison.""" @@ -826,15 +824,11 @@ class State: def __repr__(self) -> str: """Return the representation of the states.""" - attrs = ( - "; {}".format(util.repr_helper(self.attributes)) if self.attributes else "" - ) + attrs = f"; {util.repr_helper(self.attributes)}" if self.attributes else "" - return "".format( - self.entity_id, - self.state, - attrs, - dt_util.as_local(self.last_changed).isoformat(), + return ( + f"" ) @@ -1045,8 +1039,9 @@ class ServiceCall: def __repr__(self) -> str: """Return the representation of the service.""" if self.data: - return "".format( - self.domain, self.service, self.context.id, util.repr_helper(self.data) + return ( + f"" ) return f"" diff --git a/homeassistant/loader.py b/homeassistant/loader.py index 913262d35c4..3e82adeb2e2 100644 --- a/homeassistant/loader.py +++ b/homeassistant/loader.py @@ -419,9 +419,7 @@ def _load_file( parts = [] for part in path.split("."): parts.append(part) - white_listed_errors.append( - "No module named '{}'".format(".".join(parts)) - ) + white_listed_errors.append(f"No module named '{'.'.join(parts)}'") if str(err) not in white_listed_errors: _LOGGER.exception(