diff --git a/homeassistant/components/kankun/switch.py b/homeassistant/components/kankun/switch.py index 5d41b2360e9..63f289862f6 100644 --- a/homeassistant/components/kankun/switch.py +++ b/homeassistant/components/kankun/switch.py @@ -66,7 +66,7 @@ class KankunSwitch(SwitchDevice): self._hass = hass self._name = name self._state = False - self._url = "http://{}:{}{}".format(host, port, path) + self._url = f"http://{host}:{port}{path}" if user is not None: self._auth = (user, passwd) else: @@ -78,7 +78,7 @@ class KankunSwitch(SwitchDevice): try: req = requests.get( - "{}?set={}".format(self._url, newstate), auth=self._auth, timeout=5 + f"{self._url}?set={newstate}", auth=self._auth, timeout=5 ) return req.json()["ok"] except requests.RequestException: @@ -89,9 +89,7 @@ class KankunSwitch(SwitchDevice): _LOGGER.info("Querying state from: %s", self._url) try: - req = requests.get( - "{}?get=state".format(self._url), auth=self._auth, timeout=5 - ) + req = requests.get(f"{self._url}?get=state", auth=self._auth, timeout=5) return req.json()["state"] == "on" except requests.RequestException: _LOGGER.error("State query failed") diff --git a/homeassistant/components/kira/__init__.py b/homeassistant/components/kira/__init__.py index 24eb8b06aef..77f91a50dfa 100644 --- a/homeassistant/components/kira/__init__.py +++ b/homeassistant/components/kira/__init__.py @@ -32,7 +32,7 @@ CONF_REMOTES = "remotes" CONF_SENSOR = "sensor" CONF_REMOTE = "remote" -CODES_YAML = "{}_codes.yaml".format(DOMAIN) +CODES_YAML = f"{DOMAIN}_codes.yaml" CODE_SCHEMA = vol.Schema( { diff --git a/homeassistant/components/kodi/media_player.py b/homeassistant/components/kodi/media_player.py index 14ef0292ecc..9f0aab6c00c 100644 --- a/homeassistant/components/kodi/media_player.py +++ b/homeassistant/components/kodi/media_player.py @@ -140,7 +140,7 @@ def _check_deprecated_turn_off(hass, turn_off_action): method = DEPRECATED_TURN_OFF_ACTIONS[turn_off_action] new_config = OrderedDict( [ - ("service", "{}.{}".format(DOMAIN, SERVICE_CALL_METHOD)), + ("service", f"{DOMAIN}.{SERVICE_CALL_METHOD}"), ( "data_template", OrderedDict([("entity_id", "{{ entity_id }}"), ("method", method)]), @@ -281,18 +281,18 @@ class KodiDevice(MediaPlayerDevice): if username is not None: kwargs["auth"] = aiohttp.BasicAuth(username, password) - image_auth_string = "{}:{}@".format(username, password) + image_auth_string = f"{username}:{password}@" else: image_auth_string = "" http_protocol = "https" if encryption else "http" ws_protocol = "wss" if encryption else "ws" - self._http_url = "{}://{}:{}/jsonrpc".format(http_protocol, host, port) + self._http_url = f"{http_protocol}://{host}:{port}/jsonrpc" self._image_url = "{}://{}{}:{}/image".format( http_protocol, image_auth_string, host, port ) - self._ws_url = "{}://{}:{}/jsonrpc".format(ws_protocol, host, tcp_port) + self._ws_url = f"{ws_protocol}://{host}:{tcp_port}/jsonrpc" self._http_server = jsonrpc_async.Server(self._http_url, **kwargs) if websocket: @@ -326,14 +326,14 @@ class KodiDevice(MediaPlayerDevice): turn_on_action = script.Script( self.hass, turn_on_action, - "{} turn ON script".format(self.name), + f"{self.name} turn ON script", self.async_update_ha_state(True), ) if turn_off_action is not None: turn_off_action = script.Script( self.hass, _check_deprecated_turn_off(hass, turn_off_action), - "{} turn OFF script".format(self.name), + f"{self.name} turn OFF script", ) self._turn_on_action = turn_on_action self._turn_off_action = turn_off_action diff --git a/homeassistant/components/kodi/notify.py b/homeassistant/components/kodi/notify.py index 70c8669019c..41dfc42b5de 100644 --- a/homeassistant/components/kodi/notify.py +++ b/homeassistant/components/kodi/notify.py @@ -62,7 +62,7 @@ async def async_get_service(hass, config, discovery_info=None): ) http_protocol = "https" if encryption else "http" - url = "{}://{}:{}/jsonrpc".format(http_protocol, host, port) + url = f"{http_protocol}://{host}:{port}/jsonrpc" if username is not None: auth = aiohttp.BasicAuth(username, password) diff --git a/homeassistant/components/konnected/__init__.py b/homeassistant/components/konnected/__init__.py index d98f44bd3d9..4cc872fb78b 100644 --- a/homeassistant/components/konnected/__init__.py +++ b/homeassistant/components/konnected/__init__.py @@ -538,7 +538,7 @@ class KonnectedView(HomeAssistantView): ) auth = request.headers.get(AUTHORIZATION, None) - if not hmac.compare_digest("Bearer {}".format(self.auth_token), auth): + if not hmac.compare_digest(f"Bearer {self.auth_token}", auth): return self.json_message("unauthorized", status_code=HTTP_UNAUTHORIZED) pin_num = int(pin_num) device = data[CONF_DEVICES].get(device_id) diff --git a/homeassistant/components/kwb/sensor.py b/homeassistant/components/kwb/sensor.py index 911884d2a9e..49815faf7ae 100644 --- a/homeassistant/components/kwb/sensor.py +++ b/homeassistant/components/kwb/sensor.py @@ -92,7 +92,7 @@ class KWBSensor(Entity): @property def name(self): """Return the name.""" - return "{} {}".format(self._client_name, self._name) + return f"{self._client_name} {self._name}" @property def available(self) -> bool: diff --git a/homeassistant/components/lastfm/sensor.py b/homeassistant/components/lastfm/sensor.py index ce92cffee53..736792aefd8 100644 --- a/homeassistant/components/lastfm/sensor.py +++ b/homeassistant/components/lastfm/sensor.py @@ -72,7 +72,7 @@ class LastfmSensor(Entity): @property def entity_id(self): """Return the entity ID.""" - return "sensor.lastfm_{}".format(self._name) + return f"sensor.lastfm_{self._name}" @property def state(self): @@ -84,7 +84,7 @@ class LastfmSensor(Entity): self._cover = self._user.get_image() self._playcount = self._user.get_playcount() last = self._user.get_recent_tracks(limit=2)[0] - self._lastplayed = "{} - {}".format(last.track.artist, last.track.title) + self._lastplayed = f"{last.track.artist} - {last.track.title}" top = self._user.get_top_tracks(limit=1)[0] toptitle = re.search("', '(.+?)',", str(top)) topartist = re.search("'(.+?)',", str(top)) @@ -93,7 +93,7 @@ class LastfmSensor(Entity): self._state = "Not Scrobbling" return now = self._user.get_now_playing() - self._state = "{} - {}".format(now.artist, now.title) + self._state = f"{now.artist} - {now.title}" @property def device_state_attributes(self): diff --git a/homeassistant/components/lcn/helpers.py b/homeassistant/components/lcn/helpers.py index 92d51512726..236035b0400 100644 --- a/homeassistant/components/lcn/helpers.py +++ b/homeassistant/components/lcn/helpers.py @@ -38,7 +38,7 @@ def has_unique_connection_names(connections): if suffix == 0: connection[CONF_NAME] = DEFAULT_NAME else: - connection[CONF_NAME] = "{}{:d}".format(DEFAULT_NAME, suffix) + connection[CONF_NAME] = f"{DEFAULT_NAME}{suffix:d}" schema = vol.Schema(vol.Unique()) schema([connection.get(CONF_NAME) for connection in connections]) diff --git a/homeassistant/components/life360/config_flow.py b/homeassistant/components/life360/config_flow.py index be84d276422..6af999a575d 100644 --- a/homeassistant/components/life360/config_flow.py +++ b/homeassistant/components/life360/config_flow.py @@ -99,7 +99,7 @@ class Life360ConfigFlow(config_entries.ConfigFlow): ) return self.async_abort(reason="unexpected") return self.async_create_entry( - title="{} (from configuration)".format(username), + title=f"{username} (from configuration)", data={ CONF_USERNAME: username, CONF_PASSWORD: password, diff --git a/homeassistant/components/life360/device_tracker.py b/homeassistant/components/life360/device_tracker.py index dc5645a5216..ddd562ebfac 100644 --- a/homeassistant/components/life360/device_tracker.py +++ b/homeassistant/components/life360/device_tracker.py @@ -159,7 +159,7 @@ class Life360Scanner: _errs = self._errs.get(key, 0) if _errs < self._max_errs: self._errs[key] = _errs = _errs + 1 - msg = "{}: {}".format(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 @@ -233,14 +233,12 @@ class Life360Scanner: convert(float(gps_accuracy), LENGTH_FEET, LENGTH_METERS) ) except (TypeError, ValueError): - self._err( - dev_id, "GPS data invalid: {}, {}, {}".format(lat, lon, gps_accuracy) - ) + self._err(dev_id, f"GPS data invalid: {lat}, {lon}, {gps_accuracy}") return self._ok(dev_id) - msg = "Updating {}".format(dev_id) + msg = f"Updating {dev_id}" if prev_seen: msg += "; Time since last update: {}".format(last_seen - prev_seen) _LOGGER.debug(msg) @@ -401,7 +399,7 @@ class Life360Scanner: except (Life360Error, KeyError): pass if incl_circle: - err_key = 'get_circle_members "{}"'.format(circle_name) + err_key = f'get_circle_members "{circle_name}"' try: members = api.get_circle_members(circle_id) except Life360Error as exc: diff --git a/homeassistant/components/lifx/light.py b/homeassistant/components/lifx/light.py index b3ec9ed288f..ed26db3d49e 100644 --- a/homeassistant/components/lifx/light.py +++ b/homeassistant/components/lifx/light.py @@ -509,7 +509,7 @@ class LIFXLight(Light): @property def who(self): """Return a string identifying the bulb.""" - return "%s (%s)" % (self.bulb.ip_addr, self.name) + return f"{self.bulb.ip_addr} ({self.name})" @property def min_mireds(self): diff --git a/homeassistant/components/lifx_cloud/scene.py b/homeassistant/components/lifx_cloud/scene.py index 6fc9fac1267..ac4e0201fb8 100644 --- a/homeassistant/components/lifx_cloud/scene.py +++ b/homeassistant/components/lifx_cloud/scene.py @@ -31,7 +31,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info= token = config.get(CONF_TOKEN) timeout = config.get(CONF_TIMEOUT) - headers = {AUTHORIZATION: "Bearer {}".format(token)} + headers = {AUTHORIZATION: f"Bearer {token}"} url = LIFX_API_URL.format("scenes") diff --git a/homeassistant/components/light/__init__.py b/homeassistant/components/light/__init__.py index 94ba43b8545..ed61d961d88 100644 --- a/homeassistant/components/light/__init__.py +++ b/homeassistant/components/light/__init__.py @@ -237,16 +237,16 @@ class SetIntentHandler(intent.IntentHandler): response = intent_obj.create_response() if not speech_parts: # No attributes changed - speech = "Turned on {}".format(state.name) + speech = f"Turned on {state.name}" else: - parts = ["Changed {} to".format(state.name)] + parts = [f"Changed {state.name} to"] for index, part in enumerate(speech_parts): if index == 0: - parts.append(" {}".format(part)) + parts.append(f" {part}") elif index != len(speech_parts) - 1: - parts.append(", {}".format(part)) + parts.append(f", {part}") else: - parts.append(" and {}".format(part)) + parts.append(f" and {part}") speech = "".join(parts) response.async_set_speech(speech) diff --git a/homeassistant/components/linksys_smart/device_tracker.py b/homeassistant/components/linksys_smart/device_tracker.py index 9877f6ed091..1af84a4c4ab 100644 --- a/homeassistant/components/linksys_smart/device_tracker.py +++ b/homeassistant/components/linksys_smart/device_tracker.py @@ -100,7 +100,7 @@ class LinksysSmartWifiDeviceScanner(DeviceScanner): ] headers = {"X-JNAP-Action": "http://linksys.com/jnap/core/Transaction"} return requests.post( - "http://{}/JNAP/".format(self.host), + f"http://{self.host}/JNAP/", timeout=DEFAULT_TIMEOUT, headers=headers, json=data, diff --git a/homeassistant/components/linux_battery/sensor.py b/homeassistant/components/linux_battery/sensor.py index 9eb7090e957..9256c3ad18d 100644 --- a/homeassistant/components/linux_battery/sensor.py +++ b/homeassistant/components/linux_battery/sensor.py @@ -59,7 +59,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None): if system == "android": os.listdir(os.path.join(DEFAULT_PATH, "battery")) else: - os.listdir(os.path.join(DEFAULT_PATH, "BAT{}".format(battery_id))) + os.listdir(os.path.join(DEFAULT_PATH, f"BAT{battery_id}")) except FileNotFoundError: _LOGGER.error("No battery found") return False diff --git a/homeassistant/components/liveboxplaytv/media_player.py b/homeassistant/components/liveboxplaytv/media_player.py index 3c3c8bb9b38..98418d6be81 100644 --- a/homeassistant/components/liveboxplaytv/media_player.py +++ b/homeassistant/components/liveboxplaytv/media_player.py @@ -178,7 +178,7 @@ class LiveboxPlayTvDevice(MediaPlayerDevice): """Title of current playing media.""" if self._current_channel: if self._current_program: - return "{}: {}".format(self._current_channel, self._current_program) + return f"{self._current_channel}: {self._current_program}" return self._current_channel @property diff --git a/homeassistant/components/locative/__init__.py b/homeassistant/components/locative/__init__.py index e1df5b980a9..61e0b1f7474 100644 --- a/homeassistant/components/locative/__init__.py +++ b/homeassistant/components/locative/__init__.py @@ -22,7 +22,7 @@ from homeassistant.helpers.dispatcher import async_dispatcher_send _LOGGER = logging.getLogger(__name__) DOMAIN = "locative" -TRACKER_UPDATE = "{}_tracker_update".format(DOMAIN) +TRACKER_UPDATE = f"{DOMAIN}_tracker_update" ATTR_DEVICE_ID = "device" @@ -76,12 +76,10 @@ async def handle_webhook(hass, webhook_id, request): if direction == "enter": async_dispatcher_send(hass, TRACKER_UPDATE, device, gps_location, location_name) - return web.Response( - text="Setting location to {}".format(location_name), status=HTTP_OK - ) + return web.Response(text=f"Setting location to {location_name}", status=HTTP_OK) if direction == "exit": - current_state = hass.states.get("{}.{}".format(DEVICE_TRACKER, device)) + current_state = hass.states.get(f"{DEVICE_TRACKER}.{device}") if current_state is None or current_state.state == location_name: location_name = STATE_NOT_HOME @@ -108,7 +106,7 @@ async def handle_webhook(hass, webhook_id, request): _LOGGER.error("Received unidentified message from Locative: %s", direction) return web.Response( - text="Received unidentified message: {}".format(direction), + text=f"Received unidentified message: {direction}", status=HTTP_UNPROCESSABLE_ENTITY, ) diff --git a/homeassistant/components/logbook/__init__.py b/homeassistant/components/logbook/__init__.py index 0383e73105b..3c5e828765c 100644 --- a/homeassistant/components/logbook/__init__.py +++ b/homeassistant/components/logbook/__init__.py @@ -188,7 +188,7 @@ def humanify(hass, events): - if 2+ sensor updates in GROUP_BY_MINUTES, show last - if home assistant stop and start happen in same minute call it restarted """ - domain_prefixes = tuple("{}.".format(dom) for dom in CONTINUOUS_DOMAINS) + domain_prefixes = tuple(f"{dom}." for dom in CONTINUOUS_DOMAINS) # Group events in batches of GROUP_BY_MINUTES for _, g_events in groupby( @@ -332,7 +332,7 @@ def humanify(hass, events): entity_id = data.get(ATTR_ENTITY_ID) value = data.get(ATTR_VALUE) - value_msg = " to {}".format(value) if value else "" + value_msg = f" to {value}" if value else "" message = "send command {}{} for {}".format( data[ATTR_SERVICE], value_msg, data[ATTR_DISPLAY_NAME] ) @@ -519,7 +519,7 @@ def _keep_event(event, entities_filter): domain = DOMAIN_HOMEKIT if not entity_id and domain: - entity_id = "%s." % (domain,) + entity_id = f"{domain}." return not entity_id or entities_filter(entity_id) @@ -530,7 +530,7 @@ def _entry_message_from_state(domain, state): if domain in ["device_tracker", "person"]: if state.state == STATE_NOT_HOME: return "is away" - return "is at {}".format(state.state) + return f"is at {state.state}" if domain == "sun": if state.state == sun.STATE_ABOVE_HORIZON: @@ -596,9 +596,9 @@ def _entry_message_from_state(domain, state): "vibration", ]: if state.state == STATE_ON: - return "detected {}".format(device_class) + return f"detected {device_class}" if state.state == STATE_OFF: - return "cleared (no {} detected)".format(device_class) + return f"cleared (no {device_class} detected)" if state.state == STATE_ON: # Future: combine groups and its entity entries ? @@ -607,4 +607,4 @@ def _entry_message_from_state(domain, state): if state.state == STATE_OFF: return "turned off" - return "changed to {}".format(state.state) + return f"changed to {state.state}" diff --git a/homeassistant/components/logentries/__init__.py b/homeassistant/components/logentries/__init__.py index ba92fb8a672..3601ee275b8 100644 --- a/homeassistant/components/logentries/__init__.py +++ b/homeassistant/components/logentries/__init__.py @@ -24,7 +24,7 @@ def setup(hass, config): """Set up the Logentries component.""" conf = config[DOMAIN] token = conf.get(CONF_TOKEN) - le_wh = "{}{}".format(DEFAULT_HOST, token) + le_wh = f"{DEFAULT_HOST}{token}" def logentries_event_listener(event): """Listen for new messages on the bus and sends them to Logentries.""" diff --git a/homeassistant/components/logi_circle/__init__.py b/homeassistant/components/logi_circle/__init__.py index 6f073a064f1..12484a655d6 100644 --- a/homeassistant/components/logi_circle/__init__.py +++ b/homeassistant/components/logi_circle/__init__.py @@ -156,7 +156,7 @@ async def async_setup_entry(hass, entry): except asyncio.TimeoutError: # The TimeoutError exception object returns nothing when casted to a # string, so we'll handle it separately. - err = "{}s timeout exceeded when connecting to Logi Circle API".format(_TIMEOUT) + err = f"{_TIMEOUT}s timeout exceeded when connecting to Logi Circle API" hass.components.persistent_notification.create( "Error: {}
" "You will need to restart hass after fixing." diff --git a/homeassistant/components/logi_circle/config_flow.py b/homeassistant/components/logi_circle/config_flow.py index f81db9ba171..2a25c5f00a4 100644 --- a/homeassistant/components/logi_circle/config_flow.py +++ b/homeassistant/components/logi_circle/config_flow.py @@ -179,7 +179,7 @@ class LogiCircleFlowHandler(config_entries.ConfigFlow): account_id = (await logi_session.account)["accountId"] await logi_session.close() return self.async_create_entry( - title="Logi Circle ({})".format(account_id), + title=f"Logi Circle ({account_id})", data={ CONF_CLIENT_ID: client_id, CONF_CLIENT_SECRET: client_secret, diff --git a/homeassistant/components/logi_circle/sensor.py b/homeassistant/components/logi_circle/sensor.py index f229250ea09..fc5ad7155b4 100644 --- a/homeassistant/components/logi_circle/sensor.py +++ b/homeassistant/components/logi_circle/sensor.py @@ -49,7 +49,7 @@ class LogiSensor(Entity): """Initialize a sensor for Logi Circle camera.""" self._sensor_type = sensor_type self._camera = camera - self._id = "{}-{}".format(self._camera.mac_address, self._sensor_type) + self._id = f"{self._camera.mac_address}-{self._sensor_type}" self._icon = "mdi:{}".format(SENSOR_TYPES.get(self._sensor_type)[2]) self._name = "{0} {1}".format( self._camera.name, SENSOR_TYPES.get(self._sensor_type)[0] diff --git a/homeassistant/components/luftdaten/__init__.py b/homeassistant/components/luftdaten/__init__.py index e05967a91fd..86129eafc02 100644 --- a/homeassistant/components/luftdaten/__init__.py +++ b/homeassistant/components/luftdaten/__init__.py @@ -34,7 +34,7 @@ SENSOR_PM2_5 = "P2" SENSOR_PRESSURE = "pressure" SENSOR_TEMPERATURE = "temperature" -TOPIC_UPDATE = "{0}_data_update".format(DOMAIN) +TOPIC_UPDATE = f"{DOMAIN}_data_update" VOLUME_MICROGRAMS_PER_CUBIC_METER = "µg/m3" diff --git a/homeassistant/components/lutron/__init__.py b/homeassistant/components/lutron/__init__.py index 9f4d81df044..de3ca40fd1d 100644 --- a/homeassistant/components/lutron/__init__.py +++ b/homeassistant/components/lutron/__init__.py @@ -114,7 +114,7 @@ class LutronDevice(Entity): @property def name(self): """Return the name of the device.""" - return "{} {}".format(self._area_name, self._lutron_device.name) + return f"{self._area_name} {self._lutron_device.name}" @property def should_poll(self): @@ -132,7 +132,7 @@ class LutronButton: def __init__(self, hass, keypad, button): """Register callback for activity on the button.""" - name = "{}: {}".format(keypad.name, button.name) + name = f"{keypad.name}: {button.name}" self._hass = hass self._has_release_event = ( button.button_type is not None and "RaiseLower" in button.button_type diff --git a/homeassistant/components/lyft/sensor.py b/homeassistant/components/lyft/sensor.py index 0bf739b040c..339b996c5d8 100644 --- a/homeassistant/components/lyft/sensor.py +++ b/homeassistant/components/lyft/sensor.py @@ -85,7 +85,7 @@ class LyftSensor(Entity): self._sensortype = sensorType self._name = "{} {}".format(self._product["display_name"], self._sensortype) if "lyft" not in self._name.lower(): - self._name = "Lyft{}".format(self._name) + self._name = f"Lyft{self._name}" if self._sensortype == "time": self._unit_of_measurement = "min" elif self._sensortype == "price": diff --git a/homeassistant/components/magicseaweed/sensor.py b/homeassistant/components/magicseaweed/sensor.py index 61abb9788c5..66ab87a6569 100644 --- a/homeassistant/components/magicseaweed/sensor.py +++ b/homeassistant/components/magicseaweed/sensor.py @@ -108,10 +108,10 @@ class MagicSeaweedSensor(Entity): def name(self): """Return the name of the sensor.""" if self.hour is None and "forecast" in self.type: - return "{} {}".format(self.client_name, self._name) + return f"{self.client_name} {self._name}" if self.hour is None: - return "Current {} {}".format(self.client_name, self._name) - return "{} {} {}".format(self.hour, self.client_name, self._name) + return f"Current {self.client_name} {self._name}" + return f"{self.hour} {self.client_name} {self._name}" @property def state(self): diff --git a/homeassistant/components/mailgun/__init__.py b/homeassistant/components/mailgun/__init__.py index 87bbe6bee07..4bcca0848f4 100644 --- a/homeassistant/components/mailgun/__init__.py +++ b/homeassistant/components/mailgun/__init__.py @@ -19,7 +19,7 @@ CONF_SANDBOX = "sandbox" DEFAULT_SANDBOX = False -MESSAGE_RECEIVED = "{}_message_received".format(DOMAIN) +MESSAGE_RECEIVED = f"{DOMAIN}_message_received" CONFIG_SCHEMA = vol.Schema( { @@ -75,7 +75,7 @@ async def verify_webhook(hass, token=None, timestamp=None, signature=None): hmac_digest = hmac.new( key=bytes(hass.data[DOMAIN][CONF_API_KEY], "utf-8"), - msg=bytes("{}{}".format(timestamp, token), "utf-8"), + msg=bytes(f"{timestamp}{token}", "utf-8"), digestmod=hashlib.sha256, ).hexdigest() diff --git a/homeassistant/components/marytts/tts.py b/homeassistant/components/marytts/tts.py index 9f64c088b4a..e5088c5b2df 100644 --- a/homeassistant/components/marytts/tts.py +++ b/homeassistant/components/marytts/tts.py @@ -74,7 +74,7 @@ class MaryTTSProvider(Provider): try: with async_timeout.timeout(10): - url = "http://{}:{}/process?".format(self._host, self._port) + url = f"http://{self._host}:{self._port}/process?" audio = self._codec.upper() if audio == "WAV": diff --git a/homeassistant/components/metoffice/weather.py b/homeassistant/components/metoffice/weather.py index e90d6fdc4c2..bb7a64005ce 100644 --- a/homeassistant/components/metoffice/weather.py +++ b/homeassistant/components/metoffice/weather.py @@ -83,7 +83,7 @@ class MetOfficeWeather(WeatherEntity): @property def name(self): """Return the name of the sensor.""" - return "{} {}".format(self._name, self.site.name) + return f"{self._name} {self.site.name}" @property def condition(self): diff --git a/homeassistant/components/microsoft/tts.py b/homeassistant/components/microsoft/tts.py index ff06e8815ed..3536c788bb9 100644 --- a/homeassistant/components/microsoft/tts.py +++ b/homeassistant/components/microsoft/tts.py @@ -115,8 +115,8 @@ class MicrosoftProvider(Provider): self._gender = gender self._type = ttype self._output = DEFAULT_OUTPUT - self._rate = "{}%".format(rate) - self._volume = "{}%".format(volume) + self._rate = f"{rate}%" + self._volume = f"{volume}%" self._pitch = pitch self._contour = contour self.name = "Microsoft" diff --git a/homeassistant/components/microsoft_face/__init__.py b/homeassistant/components/microsoft_face/__init__.py index 6c2fc5ae6bf..5d0c50e536a 100644 --- a/homeassistant/components/microsoft_face/__init__.py +++ b/homeassistant/components/microsoft_face/__init__.py @@ -92,7 +92,7 @@ async def async_setup(hass, config): g_id = slugify(name) try: - await face.call_api("put", "persongroups/{0}".format(g_id), {"name": name}) + await face.call_api("put", f"persongroups/{g_id}", {"name": name}) face.store[g_id] = {} entities[g_id] = MicrosoftFaceGroupEntity(hass, face, g_id, name) @@ -109,7 +109,7 @@ async def async_setup(hass, config): g_id = slugify(service.data[ATTR_NAME]) try: - await face.call_api("delete", "persongroups/{0}".format(g_id)) + await face.call_api("delete", f"persongroups/{g_id}") face.store.pop(g_id) entity = entities.pop(g_id) @@ -126,7 +126,7 @@ async def async_setup(hass, config): g_id = service.data[ATTR_GROUP] try: - await face.call_api("post", "persongroups/{0}/train".format(g_id)) + await face.call_api("post", f"persongroups/{g_id}/train") except HomeAssistantError as err: _LOGGER.error("Can't train group '%s' with error: %s", g_id, err) @@ -141,7 +141,7 @@ async def async_setup(hass, config): try: user_data = await face.call_api( - "post", "persongroups/{0}/persons".format(g_id), {"name": name} + "post", f"persongroups/{g_id}/persons", {"name": name} ) face.store[g_id][name] = user_data["personId"] @@ -160,9 +160,7 @@ async def async_setup(hass, config): p_id = face.store[g_id].get(name) try: - await face.call_api( - "delete", "persongroups/{0}/persons/{1}".format(g_id, p_id) - ) + await face.call_api("delete", f"persongroups/{g_id}/persons/{p_id}") face.store[g_id].pop(name) await entities[g_id].async_update_ha_state() @@ -186,7 +184,7 @@ async def async_setup(hass, config): await face.call_api( "post", - "persongroups/{0}/persons/{1}/persistedFaces".format(g_id, p_id), + f"persongroups/{g_id}/persons/{p_id}/persistedFaces", image.content, binary=True, ) @@ -218,7 +216,7 @@ class MicrosoftFaceGroupEntity(Entity): @property def entity_id(self): """Return entity id.""" - return "{0}.{1}".format(DOMAIN, self._id) + return f"{DOMAIN}.{self._id}" @property def state(self): @@ -249,7 +247,7 @@ class MicrosoftFace: self.websession = async_get_clientsession(hass) self.timeout = timeout self._api_key = api_key - self._server_url = "https://{0}.{1}".format(server_loc, FACE_API_URL) + self._server_url = f"https://{server_loc}.{FACE_API_URL}" self._store = {} self._entities = entities @@ -270,9 +268,7 @@ class MicrosoftFace: self.hass, self, g_id, group["name"] ) - persons = await self.call_api( - "get", "persongroups/{0}/persons".format(g_id) - ) + persons = await self.call_api("get", f"persongroups/{g_id}/persons") for person in persons: self._store[g_id][person["name"]] = person["personId"] diff --git a/homeassistant/components/microsoft_face_detect/image_processing.py b/homeassistant/components/microsoft_face_detect/image_processing.py index 243b4533938..c10f7edf9db 100644 --- a/homeassistant/components/microsoft_face_detect/image_processing.py +++ b/homeassistant/components/microsoft_face_detect/image_processing.py @@ -30,7 +30,7 @@ def validate_attributes(list_attributes): """Validate face attributes.""" for attr in list_attributes: if attr not in SUPPORTED_ATTRIBUTES: - raise vol.Invalid("Invalid attribute {0}".format(attr)) + raise vol.Invalid(f"Invalid attribute {attr}") return list_attributes diff --git a/homeassistant/components/miflora/sensor.py b/homeassistant/components/miflora/sensor.py index 999dc473c60..86f1462e2cc 100644 --- a/homeassistant/components/miflora/sensor.py +++ b/homeassistant/components/miflora/sensor.py @@ -85,7 +85,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info= prefix = config.get(CONF_NAME) if prefix: - name = "{} {}".format(prefix, name) + name = f"{prefix} {name}" devs.append( MiFloraSensor(poller, parameter, name, unit, icon, force_update, median) diff --git a/homeassistant/components/minio/__init__.py b/homeassistant/components/minio/__init__.py index cede3a7aad5..d411d913082 100644 --- a/homeassistant/components/minio/__init__.py +++ b/homeassistant/components/minio/__init__.py @@ -166,7 +166,7 @@ def setup(hass, config): def get_minio_endpoint(host: str, port: int) -> str: """Create minio endpoint from host and port.""" - return "{}:{}".format(host, port) + return f"{host}:{port}" class QueueListener(threading.Thread): diff --git a/homeassistant/components/mitemp_bt/sensor.py b/homeassistant/components/mitemp_bt/sensor.py index c9b7837c683..9cd1f1cebc2 100644 --- a/homeassistant/components/mitemp_bt/sensor.py +++ b/homeassistant/components/mitemp_bt/sensor.py @@ -94,7 +94,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None): prefix = config.get(CONF_NAME) if prefix: - name = "{} {}".format(prefix, name) + name = f"{prefix} {name}" devs.append( MiTempBtSensor(poller, parameter, device, name, unit, force_update, median) diff --git a/homeassistant/components/mobile_app/binary_sensor.py b/homeassistant/components/mobile_app/binary_sensor.py index c0ea297edc1..975c4c16c32 100644 --- a/homeassistant/components/mobile_app/binary_sensor.py +++ b/homeassistant/components/mobile_app/binary_sensor.py @@ -53,7 +53,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities): async_dispatcher_connect( hass, - "{}_{}_register".format(DOMAIN, ENTITY_TYPE), + f"{DOMAIN}_{ENTITY_TYPE}_register", partial(handle_sensor_registration, webhook_id), ) diff --git a/homeassistant/components/mobile_app/entity.py b/homeassistant/components/mobile_app/entity.py index c207475dc3c..27cb9934b18 100644 --- a/homeassistant/components/mobile_app/entity.py +++ b/homeassistant/components/mobile_app/entity.py @@ -21,7 +21,7 @@ from .helpers import device_info def sensor_id(webhook_id, unique_id): """Return a unique sensor ID.""" - return "{}_{}".format(webhook_id, unique_id) + return f"{webhook_id}_{unique_id}" class MobileAppEntity(Entity): diff --git a/homeassistant/components/mobile_app/sensor.py b/homeassistant/components/mobile_app/sensor.py index d6d2247736c..b96a6f1e2f0 100644 --- a/homeassistant/components/mobile_app/sensor.py +++ b/homeassistant/components/mobile_app/sensor.py @@ -53,7 +53,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities): async_dispatcher_connect( hass, - "{}_{}_register".format(DOMAIN, ENTITY_TYPE), + f"{DOMAIN}_{ENTITY_TYPE}_register", partial(handle_sensor_registration, webhook_id), ) diff --git a/homeassistant/components/mobile_app/webhook.py b/homeassistant/components/mobile_app/webhook.py index ecbd08375e0..f95d5b993f0 100644 --- a/homeassistant/components/mobile_app/webhook.py +++ b/homeassistant/components/mobile_app/webhook.py @@ -220,13 +220,13 @@ async def handle_webhook( unique_id = data[ATTR_SENSOR_UNIQUE_ID] - unique_store_key = "{}_{}".format(webhook_id, unique_id) + unique_store_key = f"{webhook_id}_{unique_id}" if unique_store_key in hass.data[DOMAIN][entity_type]: _LOGGER.error("Refusing to re-register existing sensor %s!", unique_id) return error_response( ERR_SENSOR_DUPLICATE_UNIQUE_ID, - "{} {} already exists!".format(entity_type, unique_id), + f"{entity_type} {unique_id} already exists!", status=409, ) @@ -257,13 +257,13 @@ async def handle_webhook( unique_id = sensor[ATTR_SENSOR_UNIQUE_ID] - unique_store_key = "{}_{}".format(webhook_id, unique_id) + unique_store_key = f"{webhook_id}_{unique_id}" if unique_store_key not in hass.data[DOMAIN][entity_type]: _LOGGER.error( "Refusing to update non-registered sensor: %s", unique_store_key ) - err_msg = "{} {} is not registered".format(entity_type, unique_id) + err_msg = f"{entity_type} {unique_id} is not registered" resp[unique_id] = { "success": False, "error": {"code": ERR_SENSOR_NOT_REGISTERED, "message": err_msg}, diff --git a/homeassistant/components/mochad/light.py b/homeassistant/components/mochad/light.py index a7b0b8c2d0f..899908c34bd 100644 --- a/homeassistant/components/mochad/light.py +++ b/homeassistant/components/mochad/light.py @@ -50,7 +50,7 @@ class MochadLight(Light): self._controller = ctrl self._address = dev[CONF_ADDRESS] - self._name = dev.get(CONF_NAME, "x10_light_dev_{}".format(self._address)) + self._name = dev.get(CONF_NAME, f"x10_light_dev_{self._address}") self._comm_type = dev.get(mochad.CONF_COMM_TYPE, "pl") self.light = device.Device(ctrl, self._address, comm_type=self._comm_type) self._brightness = 0 @@ -95,12 +95,12 @@ class MochadLight(Light): if self._brightness > brightness: bdelta = self._brightness - brightness mochad_brightness = self._calculate_brightness_value(bdelta) - self.light.send_cmd("dim {}".format(mochad_brightness)) + self.light.send_cmd(f"dim {mochad_brightness}") self._controller.read_data() elif self._brightness < brightness: bdelta = brightness - self._brightness mochad_brightness = self._calculate_brightness_value(bdelta) - self.light.send_cmd("bright {}".format(mochad_brightness)) + self.light.send_cmd(f"bright {mochad_brightness}") self._controller.read_data() def turn_on(self, **kwargs): @@ -109,7 +109,7 @@ class MochadLight(Light): with mochad.REQ_LOCK: if self._brightness_levels > 32: out_brightness = self._calculate_brightness_value(brightness) - self.light.send_cmd("xdim {}".format(out_brightness)) + self.light.send_cmd(f"xdim {out_brightness}") self._controller.read_data() else: self.light.send_cmd("on") diff --git a/homeassistant/components/modbus/climate.py b/homeassistant/components/modbus/climate.py index 22b871cea20..64b45b03c95 100644 --- a/homeassistant/components/modbus/climate.py +++ b/homeassistant/components/modbus/climate.py @@ -170,7 +170,7 @@ class ModbusThermostat(ClimateDevice): [x.to_bytes(2, byteorder="big") for x in result.registers] ) val = struct.unpack(self._structure, byte_string)[0] - register_value = format(val, ".{}f".format(self._precision)) + register_value = format(val, f".{self._precision}f") return register_value def write_register(self, register, value): diff --git a/homeassistant/components/modbus/sensor.py b/homeassistant/components/modbus/sensor.py index 4fc9fb808c6..1a5c71812d6 100644 --- a/homeassistant/components/modbus/sensor.py +++ b/homeassistant/components/modbus/sensor.py @@ -54,7 +54,7 @@ def number(value: Any) -> Union[int, float]: value = float(value) return value except (TypeError, ValueError): - raise vol.Invalid("invalid number {}".format(value)) + raise vol.Invalid(f"invalid number {value}") PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( diff --git a/homeassistant/components/mopar/__init__.py b/homeassistant/components/mopar/__init__.py index 686b927b515..857dbab2a3b 100644 --- a/homeassistant/components/mopar/__init__.py +++ b/homeassistant/components/mopar/__init__.py @@ -19,7 +19,7 @@ from homeassistant.helpers.dispatcher import dispatcher_send from homeassistant.helpers.event import track_time_interval DOMAIN = "mopar" -DATA_UPDATED = "{}_data_updated".format(DOMAIN) +DATA_UPDATED = f"{DOMAIN}_data_updated" _LOGGER = logging.getLogger(__name__) diff --git a/homeassistant/components/mpchc/media_player.py b/homeassistant/components/mpchc/media_player.py index d616ec6d1e8..ae96704be58 100644 --- a/homeassistant/components/mpchc/media_player.py +++ b/homeassistant/components/mpchc/media_player.py @@ -56,7 +56,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None): host = config.get(CONF_HOST) port = config.get(CONF_PORT) - url = "{}:{}".format(host, port) + url = f"{host}:{port}" add_entities([MpcHcDevice(name, url)], True) @@ -73,9 +73,7 @@ class MpcHcDevice(MediaPlayerDevice): def update(self): """Get the latest details.""" try: - response = requests.get( - "{}/variables.html".format(self._url), data=None, timeout=3 - ) + response = requests.get(f"{self._url}/variables.html", data=None, timeout=3) mpchc_variables = re.findall(r'

(.+?)

', response.text) @@ -88,7 +86,7 @@ class MpcHcDevice(MediaPlayerDevice): """Send a command to MPC-HC via its window message ID.""" try: params = {"wm_command": command_id} - requests.get("{}/command.html".format(self._url), params=params, timeout=3) + requests.get(f"{self._url}/command.html", params=params, timeout=3) except requests.exceptions.RequestException: _LOGGER.error( "Could not send command %d to MPC-HC at: %s", command_id, self._url diff --git a/homeassistant/components/mpd/media_player.py b/homeassistant/components/mpd/media_player.py index 0d924cdd1d2..c19f8f49226 100644 --- a/homeassistant/components/mpd/media_player.py +++ b/homeassistant/components/mpd/media_player.py @@ -211,7 +211,7 @@ class MpdDevice(MediaPlayerDevice): if title is None: return name - return "{}: {}".format(name, title) + return f"{name}: {title}" @property def media_artist(self): diff --git a/homeassistant/components/mqtt/discovery.py b/homeassistant/components/mqtt/discovery.py index d611b8db13e..f393c315793 100644 --- a/homeassistant/components/mqtt/discovery.py +++ b/homeassistant/components/mqtt/discovery.py @@ -86,7 +86,7 @@ async def async_start( """Process the received message.""" payload = msg.payload topic = msg.topic - topic_trimmed = topic.replace("{}/".format(discovery_topic), "", 1) + topic_trimmed = topic.replace(f"{discovery_topic}/", "", 1) match = TOPIC_MATCHER.match(topic_trimmed) if not match: @@ -134,9 +134,7 @@ async def async_start( if payload: # Attach MQTT topic to the payload, used for debug prints - setattr( - payload, "__configuration_source__", "MQTT (topic: '{}')".format(topic) - ) + setattr(payload, "__configuration_source__", f"MQTT (topic: '{topic}')") if CONF_PLATFORM in payload and "schema" not in payload: platform = payload[CONF_PLATFORM] diff --git a/homeassistant/components/mqtt/vacuum/schema_legacy.py b/homeassistant/components/mqtt/vacuum/schema_legacy.py index 20be0dcf89c..f2fa8f8da66 100644 --- a/homeassistant/components/mqtt/vacuum/schema_legacy.py +++ b/homeassistant/components/mqtt/vacuum/schema_legacy.py @@ -339,7 +339,7 @@ class MqttVacuum( elif self._cleaning: self._status = "Cleaning" elif self._error: - self._status = "Error: {}".format(self._error) + self._status = f"Error: {self._error}" else: self._status = "Stopped" @@ -360,7 +360,7 @@ class MqttVacuum( self.hass, self._sub_state, { - "topic{}".format(i): { + f"topic{i}": { "topic": topic, "msg_callback": message_received, "qos": self._qos, @@ -550,7 +550,7 @@ class MqttVacuum( mqtt.async_publish( self.hass, self._set_fan_speed_topic, fan_speed, self._qos, self._retain ) - self._status = "Setting fan to {}...".format(fan_speed) + self._status = f"Setting fan to {fan_speed}..." self.async_write_ha_state() async def async_send_command(self, command, params=None, **kwargs): @@ -566,5 +566,5 @@ class MqttVacuum( mqtt.async_publish( self.hass, self._send_command_topic, message, self._qos, self._retain ) - self._status = "Sending command {}...".format(message) + self._status = f"Sending command {message}..." self.async_write_ha_state() diff --git a/homeassistant/components/mysensors/__init__.py b/homeassistant/components/mysensors/__init__.py index 2bde87976bc..cbedd947843 100644 --- a/homeassistant/components/mysensors/__init__.py +++ b/homeassistant/components/mysensors/__init__.py @@ -56,7 +56,7 @@ def is_persistence_file(value): """Validate that persistence file path ends in either .pickle or .json.""" if value.endswith((".json", ".pickle")): return value - raise vol.Invalid("{} does not end in either `.json` or `.pickle`".format(value)) + raise vol.Invalid(f"{value} does not end in either `.json` or `.pickle`") def deprecated(key): @@ -138,7 +138,7 @@ def _get_mysensors_name(gateway, node_id, child_id): ), node_name, ) - return "{} {}".format(node_name, child_id) + return f"{node_name} {child_id}" @callback diff --git a/homeassistant/components/mysensors/gateway.py b/homeassistant/components/mysensors/gateway.py index 28d49303835..366692205a7 100644 --- a/homeassistant/components/mysensors/gateway.py +++ b/homeassistant/components/mysensors/gateway.py @@ -44,7 +44,7 @@ def is_serial_port(value): ports = ("COM{}".format(idx + 1) for idx in range(256)) if value in ports: return value - raise vol.Invalid("{} is not a serial port".format(value)) + raise vol.Invalid(f"{value} is not a serial port") return cv.isdevice(value) diff --git a/homeassistant/components/mysensors/notify.py b/homeassistant/components/mysensors/notify.py index ac94a8559a1..99e731762df 100644 --- a/homeassistant/components/mysensors/notify.py +++ b/homeassistant/components/mysensors/notify.py @@ -26,7 +26,7 @@ class MySensorsNotificationDevice(mysensors.device.MySensorsDevice): def __repr__(self): """Return the representation.""" - return "".format(self.name) + return f"" class MySensorsNotificationService(BaseNotificationService): diff --git a/homeassistant/components/mystrom/binary_sensor.py b/homeassistant/components/mystrom/binary_sensor.py index 20d32be199e..ff0063a380e 100644 --- a/homeassistant/components/mystrom/binary_sensor.py +++ b/homeassistant/components/mystrom/binary_sensor.py @@ -41,19 +41,16 @@ class MyStromView(HomeAssistantView): if button_action is None: _LOGGER.error("Received unidentified message from myStrom button: %s", data) - return ( - "Received unidentified message: {}".format(data), - HTTP_UNPROCESSABLE_ENTITY, - ) + return (f"Received unidentified message: {data}", HTTP_UNPROCESSABLE_ENTITY) button_id = data[button_action] - entity_id = "{}.{}_{}".format(DOMAIN, button_id, button_action) + entity_id = f"{DOMAIN}.{button_id}_{button_action}" if entity_id not in self.buttons: _LOGGER.info( "New myStrom button/action detected: %s/%s", button_id, button_action ) self.buttons[entity_id] = MyStromBinarySensor( - "{}_{}".format(button_id, button_action) + f"{button_id}_{button_action}" ) self.add_entities([self.buttons[entity_id]]) else: