diff --git a/homeassistant/components/habitica/__init__.py b/homeassistant/components/habitica/__init__.py
index 52326555aab..78c47bf9635 100644
--- a/homeassistant/components/habitica/__init__.py
+++ b/homeassistant/components/habitica/__init__.py
@@ -80,7 +80,7 @@ SERVICE_API_CALL = "api_call"
ATTR_NAME = CONF_NAME
ATTR_PATH = CONF_PATH
ATTR_ARGS = "args"
-EVENT_API_CALL_SUCCESS = "{0}_{1}_{2}".format(DOMAIN, SERVICE_API_CALL, "success")
+EVENT_API_CALL_SUCCESS = f"{DOMAIN}_{SERVICE_API_CALL}_success"
SERVICE_API_CALL_SCHEMA = vol.Schema(
{
diff --git a/homeassistant/components/harmony/remote.py b/homeassistant/components/harmony/remote.py
index bcc9d72ad08..126ce0ff992 100644
--- a/homeassistant/components/harmony/remote.py
+++ b/homeassistant/components/harmony/remote.py
@@ -111,9 +111,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
activity,
)
- harmony_conf_file = hass.config.path(
- "{}{}{}".format("harmony_", slugify(name), ".conf")
- )
+ harmony_conf_file = hass.config.path(f"harmony_{slugify(name)}.conf")
try:
device = HarmonyRemote(
name, address, port, activity, harmony_conf_file, delay_secs
diff --git a/homeassistant/components/haveibeenpwned/sensor.py b/homeassistant/components/haveibeenpwned/sensor.py
index 99f94499478..00a39aae8f4 100644
--- a/homeassistant/components/haveibeenpwned/sensor.py
+++ b/homeassistant/components/haveibeenpwned/sensor.py
@@ -81,13 +81,11 @@ class HaveIBeenPwnedSensor(Entity):
return val
for idx, value in enumerate(self._data.data[self._email]):
- tmpname = "breach {}".format(idx + 1)
- tmpvalue = "{} {}".format(
- value["Title"],
- dt_util.as_local(dt_util.parse_datetime(value["AddedDate"])).strftime(
- DATE_STR_FORMAT
- ),
+ tmpname = f"breach {idx + 1}"
+ datetime_local = dt_util.as_local(
+ dt_util.parse_datetime(value["AddedDate"])
)
+ tmpvalue = f"{value['Title']} {datetime_local.strftime(DATE_STR_FORMAT)}"
val[tmpname] = tmpvalue
return val
diff --git a/homeassistant/components/heos/config_flow.py b/homeassistant/components/heos/config_flow.py
index 7e7fe067874..91dbc19ac95 100644
--- a/homeassistant/components/heos/config_flow.py
+++ b/homeassistant/components/heos/config_flow.py
@@ -27,9 +27,7 @@ class HeosFlowHandler(config_entries.ConfigFlow):
"""Handle a discovered Heos device."""
# Store discovered host
hostname = urlparse(discovery_info[ssdp.ATTR_SSDP_LOCATION]).hostname
- friendly_name = "{} ({})".format(
- discovery_info[ssdp.ATTR_UPNP_FRIENDLY_NAME], hostname
- )
+ friendly_name = f"{discovery_info[ssdp.ATTR_UPNP_FRIENDLY_NAME]} ({hostname})"
self.hass.data.setdefault(DATA_DISCOVERED_HOSTS, {})
self.hass.data[DATA_DISCOVERED_HOSTS][friendly_name] = hostname
# Abort if other flows in progress or an entry already exists
diff --git a/homeassistant/components/here_travel_time/sensor.py b/homeassistant/components/here_travel_time/sensor.py
index 8113548b5ca..4c7652484d6 100644
--- a/homeassistant/components/here_travel_time/sensor.py
+++ b/homeassistant/components/here_travel_time/sensor.py
@@ -315,7 +315,7 @@ class HERETravelTimeSensor(Entity):
return self._get_location_from_attributes(entity)
# Check if device is in a zone
- zone_entity = self.hass.states.get("zone.{}".format(entity.state))
+ zone_entity = self.hass.states.get(f"zone.{entity.state}")
if location.has_location(zone_entity):
_LOGGER.debug(
"%s is in %s, getting zone location", entity_id, zone_entity.entity_id
@@ -348,7 +348,7 @@ class HERETravelTimeSensor(Entity):
def _get_location_from_attributes(entity: State) -> str:
"""Get the lat/long string from an entities attributes."""
attr = entity.attributes
- return "{},{}".format(attr.get(ATTR_LATITUDE), attr.get(ATTR_LONGITUDE))
+ return f"{attr.get(ATTR_LATITUDE)},{attr.get(ATTR_LONGITUDE)}"
class HERETravelTimeData:
diff --git a/homeassistant/components/hikvision/binary_sensor.py b/homeassistant/components/hikvision/binary_sensor.py
index 9db91217300..140f6908dce 100644
--- a/homeassistant/components/hikvision/binary_sensor.py
+++ b/homeassistant/components/hikvision/binary_sensor.py
@@ -109,7 +109,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
for channel in channel_list:
# Build sensor name, then parse customize config.
if data.type == "NVR":
- sensor_name = "{}_{}".format(sensor.replace(" ", "_"), channel[1])
+ sensor_name = f"{sensor.replace(' ', '_')}_{channel[1]}"
else:
sensor_name = sensor.replace(" ", "_")
diff --git a/homeassistant/components/hlk_sw16/__init__.py b/homeassistant/components/hlk_sw16/__init__.py
index 5ab16ed17e6..1750e9b0ff4 100644
--- a/homeassistant/components/hlk_sw16/__init__.py
+++ b/homeassistant/components/hlk_sw16/__init__.py
@@ -30,8 +30,6 @@ DEFAULT_PORT = 8080
DOMAIN = "hlk_sw16"
-SIGNAL_AVAILABILITY = "hlk_sw16_device_available_{}"
-
SWITCH_SCHEMA = vol.Schema({vol.Optional(CONF_NAME): cv.string})
RELAY_ID = vol.All(
@@ -74,13 +72,13 @@ async def async_setup(hass, config):
def disconnected():
"""Schedule reconnect after connection has been lost."""
_LOGGER.warning("HLK-SW16 %s disconnected", device)
- async_dispatcher_send(hass, SIGNAL_AVAILABILITY.format(device), False)
+ async_dispatcher_send(hass, f"hlk_sw16_device_available_{device}", False)
@callback
def reconnected():
"""Schedule reconnect after connection has been lost."""
_LOGGER.warning("HLK-SW16 %s connected", device)
- async_dispatcher_send(hass, SIGNAL_AVAILABILITY.format(device), True)
+ async_dispatcher_send(hass, f"hlk_sw16_device_available_{device}", True)
async def connect():
"""Set up connection and hook it into HA for reconnect/shutdown."""
@@ -168,6 +166,6 @@ class SW16Device(Entity):
self._is_on = await self._client.status(self._device_port)
async_dispatcher_connect(
self.hass,
- SIGNAL_AVAILABILITY.format(self._device_id),
+ f"hlk_sw16_device_available_{self._device_id}",
self._availability_callback,
)
diff --git a/homeassistant/components/homekit/type_media_players.py b/homeassistant/components/homekit/type_media_players.py
index 3c5dce4fa7a..e07e9cb4749 100644
--- a/homeassistant/components/homekit/type_media_players.py
+++ b/homeassistant/components/homekit/type_media_players.py
@@ -146,7 +146,7 @@ class MediaPlayer(HomeAccessory):
def generate_service_name(self, mode):
"""Generate name for individual service."""
- return "{} {}".format(self.display_name, MODE_FRIENDLY_NAME[mode])
+ return f"{self.display_name} {MODE_FRIENDLY_NAME[mode]}"
def set_on_off(self, value):
"""Move switch state to value if call came from HomeKit."""
@@ -287,7 +287,7 @@ class TelevisionMediaPlayer(HomeAccessory):
)
serv_tv.add_linked_service(serv_speaker)
- name = "{} {}".format(self.display_name, "Volume")
+ name = f"{self.display_name} Volume"
serv_speaker.configure_char(CHAR_NAME, value=name)
serv_speaker.configure_char(CHAR_ACTIVE, value=1)
diff --git a/homeassistant/components/homekit/util.py b/homeassistant/components/homekit/util.py
index 0fe97cfca63..c12f49e1b9c 100644
--- a/homeassistant/components/homekit/util.py
+++ b/homeassistant/components/homekit/util.py
@@ -102,9 +102,7 @@ def validate_entity_config(values):
domain, _ = split_entity_id(entity)
if not isinstance(config, dict):
- raise vol.Invalid(
- "The configuration for {} must be a dictionary.".format(entity)
- )
+ raise vol.Invalid(f"The configuration for {entity} must be a dictionary.")
if domain in ("alarm_control_panel", "lock"):
config = CODE_SCHEMA(config)
@@ -212,8 +210,8 @@ def show_setup_message(hass, pincode):
pin = pincode.decode()
_LOGGER.info("Pincode: %s", pin)
message = (
- "To set up Home Assistant in the Home App, enter the "
- "following code:\n### {}".format(pin)
+ f"To set up Home Assistant in the Home App, enter the "
+ f"following code:\n### {pin}"
)
hass.components.persistent_notification.create(
message, "HomeKit Setup", HOMEKIT_NOTIFY_ID
diff --git a/homeassistant/components/homekit_controller/config_flow.py b/homeassistant/components/homekit_controller/config_flow.py
index dbfb8dcbcd9..81dcfdc8f9a 100644
--- a/homeassistant/components/homekit_controller/config_flow.py
+++ b/homeassistant/components/homekit_controller/config_flow.py
@@ -73,7 +73,7 @@ def ensure_pin_format(pin):
match = PIN_FORMAT.search(pin)
if not match:
raise aiohomekit.exceptions.MalformedPinError(f"Invalid PIN code f{pin}")
- return "{}-{}-{}".format(*match.groups())
+ return "-".join(match.groups())
@config_entries.HANDLERS.register(DOMAIN)
diff --git a/homeassistant/components/homematic/entity.py b/homeassistant/components/homematic/entity.py
index 54811c3ccdf..49d3ee1f170 100644
--- a/homeassistant/components/homematic/entity.py
+++ b/homeassistant/components/homematic/entity.py
@@ -200,7 +200,7 @@ class HMHub(Entity):
def __init__(self, hass, homematic, name):
"""Initialize HomeMatic hub."""
self.hass = hass
- self.entity_id = "{}.{}".format(DOMAIN, name.lower())
+ self.entity_id = f"{DOMAIN}.{name.lower()}"
self._homematic = homematic
self._variables = {}
self._name = name
diff --git a/homeassistant/components/homeworks/__init__.py b/homeassistant/components/homeworks/__init__.py
index c6296d8f4c6..7ae3d30de90 100644
--- a/homeassistant/components/homeworks/__init__.py
+++ b/homeassistant/components/homeworks/__init__.py
@@ -22,7 +22,6 @@ _LOGGER = logging.getLogger(__name__)
DOMAIN = "homeworks"
HOMEWORKS_CONTROLLER = "homeworks"
-ENTITY_SIGNAL = "homeworks_entity_{}"
EVENT_BUTTON_PRESS = "homeworks_button_press"
EVENT_BUTTON_RELEASE = "homeworks_button_release"
@@ -71,7 +70,7 @@ def setup(hass, base_config):
"""Dispatch state changes."""
_LOGGER.debug("callback: %s, %s", msg_type, values)
addr = values[0]
- signal = ENTITY_SIGNAL.format(addr)
+ signal = f"homeworks_entity_{addr}"
dispatcher_send(hass, signal, msg_type, values)
config = base_config.get(DOMAIN)
@@ -132,7 +131,7 @@ class HomeworksKeypadEvent:
self._addr = addr
self._name = name
self._id = slugify(self._name)
- signal = ENTITY_SIGNAL.format(self._addr)
+ signal = f"homeworks_entity_{self._addr}"
async_dispatcher_connect(self._hass, signal, self._update_callback)
@callback
diff --git a/homeassistant/components/homeworks/light.py b/homeassistant/components/homeworks/light.py
index 2c0034ee986..56d5bcacc47 100644
--- a/homeassistant/components/homeworks/light.py
+++ b/homeassistant/components/homeworks/light.py
@@ -8,14 +8,7 @@ from homeassistant.const import CONF_NAME
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
-from . import (
- CONF_ADDR,
- CONF_DIMMERS,
- CONF_RATE,
- ENTITY_SIGNAL,
- HOMEWORKS_CONTROLLER,
- HomeworksDevice,
-)
+from . import CONF_ADDR, CONF_DIMMERS, CONF_RATE, HOMEWORKS_CONTROLLER, HomeworksDevice
_LOGGER = logging.getLogger(__name__)
@@ -47,7 +40,7 @@ class HomeworksLight(HomeworksDevice, Light):
async def async_added_to_hass(self):
"""Call when entity is added to hass."""
- signal = ENTITY_SIGNAL.format(self._addr)
+ signal = f"homeworks_entity_{self._addr}"
_LOGGER.debug("connecting %s", signal)
async_dispatcher_connect(self.hass, signal, self._update_callback)
self._controller.request_dimmer_level(self._addr)
diff --git a/homeassistant/components/hp_ilo/sensor.py b/homeassistant/components/hp_ilo/sensor.py
index 04c715dc010..888fa2423ad 100644
--- a/homeassistant/components/hp_ilo/sensor.py
+++ b/homeassistant/components/hp_ilo/sensor.py
@@ -90,9 +90,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
new_device = HpIloSensor(
hass=hass,
hp_ilo_data=hp_ilo_data,
- sensor_name="{} {}".format(
- config.get(CONF_NAME), monitored_variable[CONF_NAME]
- ),
+ sensor_name=f"{config.get(CONF_NAME)} {monitored_variable[CONF_NAME]}",
sensor_type=monitored_variable[CONF_SENSOR_TYPE],
sensor_value_template=monitored_variable.get(CONF_VALUE_TEMPLATE),
unit_of_measurement=monitored_variable.get(CONF_UNIT_OF_MEASUREMENT),
diff --git a/homeassistant/components/html5/notify.py b/homeassistant/components/html5/notify.py
index b966f5ae6a1..679968d1b8d 100644
--- a/homeassistant/components/html5/notify.py
+++ b/homeassistant/components/html5/notify.py
@@ -392,7 +392,7 @@ class HTML5PushCallbackView(HomeAssistantView):
humanize_error(event_payload, ex),
)
- event_name = "{}.{}".format(NOTIFY_CALLBACK_EVENT, event_payload[ATTR_TYPE])
+ event_name = f"{NOTIFY_CALLBACK_EVENT}.{event_payload[ATTR_TYPE]}"
request.app["hass"].bus.fire(event_name, event_payload)
return self.json({"status": "ok", "event": event_payload[ATTR_TYPE]})
diff --git a/homeassistant/components/http/auth.py b/homeassistant/components/http/auth.py
index 58814b77e2d..18d8ce72d91 100644
--- a/homeassistant/components/http/auth.py
+++ b/homeassistant/components/http/auth.py
@@ -29,20 +29,12 @@ def async_sign_path(hass, refresh_token_id, path, expiration):
secret = hass.data[DATA_SIGN_SECRET] = secrets.token_hex()
now = dt_util.utcnow()
- return "{}?{}={}".format(
- path,
- SIGN_QUERY_PARAM,
- jwt.encode(
- {
- "iss": refresh_token_id,
- "path": path,
- "iat": now,
- "exp": now + expiration,
- },
- secret,
- algorithm="HS256",
- ).decode(),
+ encoded = jwt.encode(
+ {"iss": refresh_token_id, "path": path, "iat": now, "exp": now + expiration},
+ secret,
+ algorithm="HS256",
)
+ return f"{path}?{SIGN_QUERY_PARAM}=" f"{encoded.decode()}"
@callback
diff --git a/homeassistant/components/http/ban.py b/homeassistant/components/http/ban.py
index da406c071e4..38eda8e9b3f 100644
--- a/homeassistant/components/http/ban.py
+++ b/homeassistant/components/http/ban.py
@@ -96,9 +96,7 @@ async def process_wrong_login(request):
"""
remote_addr = request[KEY_REAL_IP]
- msg = "Login attempt or request with invalid authentication from {}".format(
- remote_addr
- )
+ msg = f"Login attempt or request with invalid authentication from {remote_addr}"
_LOGGER.warning(msg)
hass = request.app["hass"]
diff --git a/homeassistant/components/http/view.py b/homeassistant/components/http/view.py
index e60091684d3..bb7c5816c77 100644
--- a/homeassistant/components/http/view.py
+++ b/homeassistant/components/http/view.py
@@ -144,9 +144,7 @@ def request_handler_factory(view, handler):
elif not isinstance(result, bytes):
assert (
False
- ), "Result should be None, string, bytes or Response. Got: {}".format(
- result
- )
+ ), f"Result should be None, string, bytes or Response. Got: {result}"
return web.Response(body=result, status=status_code)
diff --git a/homeassistant/components/huawei_lte/__init__.py b/homeassistant/components/huawei_lte/__init__.py
index d3b2d5b1abd..1bcdd7129c7 100644
--- a/homeassistant/components/huawei_lte/__init__.py
+++ b/homeassistant/components/huawei_lte/__init__.py
@@ -81,8 +81,6 @@ _LOGGER = logging.getLogger(__name__)
# https://github.com/quandyfactory/dicttoxml/issues/60
logging.getLogger("dicttoxml").setLevel(logging.WARNING)
-DEFAULT_NAME_TEMPLATE = "Huawei {} {}"
-
SCAN_INTERVAL = timedelta(seconds=10)
NOTIFY_SCHEMA = vol.Any(
@@ -567,7 +565,7 @@ class HuaweiLteBaseEntity(Entity):
@property
def name(self) -> str:
"""Return entity name."""
- return DEFAULT_NAME_TEMPLATE.format(self.router.device_name, self._entity_name)
+ return f"Huawei {self.router.device_name} {self._entity_name}"
@property
def available(self) -> bool:
diff --git a/homeassistant/components/hydrawise/__init__.py b/homeassistant/components/hydrawise/__init__.py
index b8ed596d286..65b7b1f6f6e 100644
--- a/homeassistant/components/hydrawise/__init__.py
+++ b/homeassistant/components/hydrawise/__init__.py
@@ -84,9 +84,7 @@ def setup(hass, config):
except (ConnectTimeout, HTTPError) as ex:
_LOGGER.error("Unable to connect to Hydrawise 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,
)
@@ -119,10 +117,7 @@ class HydrawiseEntity(Entity):
"""Initialize the Hydrawise entity."""
self.data = data
self._sensor_type = sensor_type
- self._name = "{0} {1}".format(
- self.data["name"],
- DEVICE_MAP[self._sensor_type][DEVICE_MAP_INDEX.index("KEY_INDEX")],
- )
+ self._name = f"{self.data['name']} {DEVICE_MAP[self._sensor_type][DEVICE_MAP_INDEX.index('KEY_INDEX')]}"
self._state = None
@property
diff --git a/homeassistant/components/ign_sismologia/geo_location.py b/homeassistant/components/ign_sismologia/geo_location.py
index deecc389e7e..21e8e1c7412 100644
--- a/homeassistant/components/ign_sismologia/geo_location.py
+++ b/homeassistant/components/ign_sismologia/geo_location.py
@@ -37,9 +37,6 @@ DEFAULT_UNIT_OF_MEASUREMENT = "km"
SCAN_INTERVAL = timedelta(minutes=5)
-SIGNAL_DELETE_ENTITY = "ign_sismologia_delete_{}"
-SIGNAL_UPDATE_ENTITY = "ign_sismologia_update_{}"
-
SOURCE = "ign_sismologia"
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
@@ -124,11 +121,11 @@ class IgnSismologiaFeedEntityManager:
def _update_entity(self, external_id):
"""Update entity."""
- dispatcher_send(self._hass, SIGNAL_UPDATE_ENTITY.format(external_id))
+ dispatcher_send(self._hass, f"ign_sismologia_update_{external_id}")
def _remove_entity(self, external_id):
"""Remove entity."""
- dispatcher_send(self._hass, SIGNAL_DELETE_ENTITY.format(external_id))
+ dispatcher_send(self._hass, f"ign_sismologia_delete_{external_id}")
class IgnSismologiaLocationEvent(GeolocationEvent):
@@ -154,12 +151,12 @@ class IgnSismologiaLocationEvent(GeolocationEvent):
"""Call when entity is added to hass."""
self._remove_signal_delete = async_dispatcher_connect(
self.hass,
- SIGNAL_DELETE_ENTITY.format(self._external_id),
+ f"ign_sismologia_delete_{self._external_id}",
self._delete_callback,
)
self._remove_signal_update = async_dispatcher_connect(
self.hass,
- SIGNAL_UPDATE_ENTITY.format(self._external_id),
+ f"ign_sismologia_update_{self._external_id}",
self._update_callback,
)
diff --git a/homeassistant/components/ihc/__init__.py b/homeassistant/components/ihc/__init__.py
index 9acf710a58e..f200c9651f0 100644
--- a/homeassistant/components/ihc/__init__.py
+++ b/homeassistant/components/ihc/__init__.py
@@ -53,7 +53,6 @@ AUTO_SETUP_YAML = "ihc_auto_setup.yaml"
DOMAIN = "ihc"
IHC_CONTROLLER = "controller"
-IHC_DATA = "ihc{}"
IHC_INFO = "info"
IHC_PLATFORMS = ("binary_sensor", "light", "sensor", "switch")
@@ -236,7 +235,7 @@ def ihc_setup(hass, config, conf, controller_id):
# Manual configuration
get_manual_configuration(hass, config, conf, ihc_controller, controller_id)
# Store controller configuration
- ihc_key = IHC_DATA.format(controller_id)
+ ihc_key = f"ihc{controller_id}"
hass.data[ihc_key] = {IHC_CONTROLLER: ihc_controller, IHC_INFO: conf[CONF_INFO]}
setup_service_functions(hass, ihc_controller)
return True
diff --git a/homeassistant/components/ihc/binary_sensor.py b/homeassistant/components/ihc/binary_sensor.py
index 00e43008342..3f59d7981fb 100644
--- a/homeassistant/components/ihc/binary_sensor.py
+++ b/homeassistant/components/ihc/binary_sensor.py
@@ -2,7 +2,7 @@
from homeassistant.components.binary_sensor import BinarySensorDevice
from homeassistant.const import CONF_TYPE
-from . import IHC_CONTROLLER, IHC_DATA, IHC_INFO
+from . import IHC_CONTROLLER, IHC_INFO
from .const import CONF_INVERTING
from .ihcdevice import IHCDevice
@@ -18,7 +18,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
product = device["product"]
# Find controller that corresponds with device id
ctrl_id = device["ctrl_id"]
- ihc_key = IHC_DATA.format(ctrl_id)
+ ihc_key = f"ihc{ctrl_id}"
info = hass.data[ihc_key][IHC_INFO]
ihc_controller = hass.data[ihc_key][IHC_CONTROLLER]
diff --git a/homeassistant/components/ihc/light.py b/homeassistant/components/ihc/light.py
index cb8bb424c8e..af6b62c42ff 100644
--- a/homeassistant/components/ihc/light.py
+++ b/homeassistant/components/ihc/light.py
@@ -3,7 +3,7 @@ import logging
from homeassistant.components.light import ATTR_BRIGHTNESS, SUPPORT_BRIGHTNESS, Light
-from . import IHC_CONTROLLER, IHC_DATA, IHC_INFO
+from . import IHC_CONTROLLER, IHC_INFO
from .const import CONF_DIMMABLE, CONF_OFF_ID, CONF_ON_ID
from .ihcdevice import IHCDevice
from .util import async_pulse, async_set_bool, async_set_int
@@ -22,7 +22,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
product = device["product"]
# Find controller that corresponds with device id
ctrl_id = device["ctrl_id"]
- ihc_key = IHC_DATA.format(ctrl_id)
+ ihc_key = f"ihc{ctrl_id}"
info = hass.data[ihc_key][IHC_INFO]
ihc_controller = hass.data[ihc_key][IHC_CONTROLLER]
ihc_off_id = product_cfg.get(CONF_OFF_ID)
diff --git a/homeassistant/components/ihc/sensor.py b/homeassistant/components/ihc/sensor.py
index 71c9fa12ba1..cb1688bc7be 100644
--- a/homeassistant/components/ihc/sensor.py
+++ b/homeassistant/components/ihc/sensor.py
@@ -2,7 +2,7 @@
from homeassistant.const import CONF_UNIT_OF_MEASUREMENT
from homeassistant.helpers.entity import Entity
-from . import IHC_CONTROLLER, IHC_DATA, IHC_INFO
+from . import IHC_CONTROLLER, IHC_INFO
from .ihcdevice import IHCDevice
@@ -17,7 +17,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
product = device["product"]
# Find controller that corresponds with device id
ctrl_id = device["ctrl_id"]
- ihc_key = IHC_DATA.format(ctrl_id)
+ ihc_key = f"ihc{ctrl_id}"
info = hass.data[ihc_key][IHC_INFO]
ihc_controller = hass.data[ihc_key][IHC_CONTROLLER]
unit = product_cfg[CONF_UNIT_OF_MEASUREMENT]
diff --git a/homeassistant/components/ihc/switch.py b/homeassistant/components/ihc/switch.py
index ebe9fcce37b..15994f13eb2 100644
--- a/homeassistant/components/ihc/switch.py
+++ b/homeassistant/components/ihc/switch.py
@@ -1,7 +1,7 @@
"""Support for IHC switches."""
from homeassistant.components.switch import SwitchDevice
-from . import IHC_CONTROLLER, IHC_DATA, IHC_INFO
+from . import IHC_CONTROLLER, IHC_INFO
from .const import CONF_OFF_ID, CONF_ON_ID
from .ihcdevice import IHCDevice
from .util import async_pulse, async_set_bool
@@ -18,7 +18,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
product = device["product"]
# Find controller that corresponds with device id
ctrl_id = device["ctrl_id"]
- ihc_key = IHC_DATA.format(ctrl_id)
+ ihc_key = f"ihc{ctrl_id}"
info = hass.data[ihc_key][IHC_INFO]
ihc_controller = hass.data[ihc_key][IHC_CONTROLLER]
ihc_off_id = product_cfg.get(CONF_OFF_ID)
diff --git a/homeassistant/components/imap_email_content/sensor.py b/homeassistant/components/imap_email_content/sensor.py
index 307d5a22c1e..a97d2a1d02b 100644
--- a/homeassistant/components/imap_email_content/sensor.py
+++ b/homeassistant/components/imap_email_content/sensor.py
@@ -113,7 +113,7 @@ class EmailReader:
self.connection.select(self._folder, readonly=True)
if not self._unread_ids:
- search = "SINCE {0:%d-%b-%Y}".format(datetime.date.today())
+ search = f"SINCE {datetime.date.today():%d-%b-%Y}"
if self._last_id is not None:
search = f"UID {self._last_id}:*"
diff --git a/homeassistant/components/incomfort/binary_sensor.py b/homeassistant/components/incomfort/binary_sensor.py
index 150515cbbf5..f15c2298b9d 100644
--- a/homeassistant/components/incomfort/binary_sensor.py
+++ b/homeassistant/components/incomfort/binary_sensor.py
@@ -1,7 +1,10 @@
"""Support for an Intergas heater via an InComfort/InTouch Lan2RF gateway."""
from typing import Any, Dict, Optional
-from homeassistant.components.binary_sensor import ENTITY_ID_FORMAT, BinarySensorDevice
+from homeassistant.components.binary_sensor import (
+ DOMAIN as BINARY_SENSOR_DOMAIN,
+ BinarySensorDevice,
+)
from . import DOMAIN, IncomfortChild
@@ -25,7 +28,7 @@ class IncomfortFailed(IncomfortChild, BinarySensorDevice):
super().__init__()
self._unique_id = f"{heater.serial_no}_failed"
- self.entity_id = ENTITY_ID_FORMAT.format(f"{DOMAIN}_failed")
+ self.entity_id = f"{BINARY_SENSOR_DOMAIN}.{DOMAIN}_failed"
self._name = "Boiler Fault"
self._client = client
diff --git a/homeassistant/components/incomfort/climate.py b/homeassistant/components/incomfort/climate.py
index 23bda6b2fdf..7d91ca012b9 100644
--- a/homeassistant/components/incomfort/climate.py
+++ b/homeassistant/components/incomfort/climate.py
@@ -1,7 +1,7 @@
"""Support for an Intergas boiler via an InComfort/InTouch Lan2RF gateway."""
from typing import Any, Dict, List, Optional
-from homeassistant.components.climate import ENTITY_ID_FORMAT, ClimateDevice
+from homeassistant.components.climate import DOMAIN as CLIMATE_DOMAIN, ClimateDevice
from homeassistant.components.climate.const import (
HVAC_MODE_HEAT,
SUPPORT_TARGET_TEMPERATURE,
@@ -32,7 +32,7 @@ class InComfortClimate(IncomfortChild, ClimateDevice):
super().__init__()
self._unique_id = f"{heater.serial_no}_{room.room_no}"
- self.entity_id = ENTITY_ID_FORMAT.format(f"{DOMAIN}_{room.room_no}")
+ self.entity_id = f"{CLIMATE_DOMAIN}.{DOMAIN}_{room.room_no}"
self._name = f"Thermostat {room.room_no}"
self._client = client
diff --git a/homeassistant/components/incomfort/sensor.py b/homeassistant/components/incomfort/sensor.py
index 4164225b0d7..692eecf2317 100644
--- a/homeassistant/components/incomfort/sensor.py
+++ b/homeassistant/components/incomfort/sensor.py
@@ -1,7 +1,7 @@
"""Support for an Intergas heater via an InComfort/InTouch Lan2RF gateway."""
from typing import Any, Dict, Optional
-from homeassistant.components.sensor import ENTITY_ID_FORMAT
+from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.const import (
DEVICE_CLASS_PRESSURE,
DEVICE_CLASS_TEMPERATURE,
@@ -49,7 +49,7 @@ class IncomfortSensor(IncomfortChild):
self._heater = heater
self._unique_id = f"{heater.serial_no}_{slugify(name)}"
- self.entity_id = ENTITY_ID_FORMAT.format(f"{DOMAIN}_{slugify(name)}")
+ self.entity_id = f"{SENSOR_DOMAIN}.{DOMAIN}_{slugify(name)}"
self._name = f"Boiler {name}"
self._device_class = None
diff --git a/homeassistant/components/incomfort/water_heater.py b/homeassistant/components/incomfort/water_heater.py
index 9096a7cb72c..88370acf166 100644
--- a/homeassistant/components/incomfort/water_heater.py
+++ b/homeassistant/components/incomfort/water_heater.py
@@ -5,7 +5,10 @@ from typing import Any, Dict
from aiohttp import ClientResponseError
-from homeassistant.components.water_heater import ENTITY_ID_FORMAT, WaterHeaterDevice
+from homeassistant.components.water_heater import (
+ DOMAIN as WATER_HEATER_DOMAIN,
+ WaterHeaterDevice,
+)
from homeassistant.const import TEMP_CELSIUS
from homeassistant.helpers.dispatcher import async_dispatcher_send
@@ -35,7 +38,7 @@ class IncomfortWaterHeater(IncomfortEntity, WaterHeaterDevice):
super().__init__()
self._unique_id = f"{heater.serial_no}"
- self.entity_id = ENTITY_ID_FORMAT.format(DOMAIN)
+ self.entity_id = f"{WATER_HEATER_DOMAIN}.{DOMAIN}"
self._name = "Boiler"
self._client = client
diff --git a/homeassistant/components/influxdb/sensor.py b/homeassistant/components/influxdb/sensor.py
index 4a169453e35..9d0eaa84340 100644
--- a/homeassistant/components/influxdb/sensor.py
+++ b/homeassistant/components/influxdb/sensor.py
@@ -196,9 +196,7 @@ class InfluxSensorData:
_LOGGER.error("Could not render where clause template: %s", ex)
return
- self.query = "select {}({}) as value from {} where {}".format(
- self.group, self.field, self.measurement, where_clause
- )
+ self.query = f"select {self.group}({self.field}) as value from {self.measurement} where {where_clause}"
_LOGGER.info("Running query: %s", self.query)
diff --git a/homeassistant/components/input_boolean/__init__.py b/homeassistant/components/input_boolean/__init__.py
index daadfac3705..603aa826123 100644
--- a/homeassistant/components/input_boolean/__init__.py
+++ b/homeassistant/components/input_boolean/__init__.py
@@ -28,8 +28,6 @@ from homeassistant.loader import bind_hass
DOMAIN = "input_boolean"
-ENTITY_ID_FORMAT = DOMAIN + ".{}"
-
_LOGGER = logging.getLogger(__name__)
CONF_INITIAL = "initial"
@@ -155,7 +153,7 @@ class InputBoolean(ToggleEntity, RestoreEntity):
self._state = config.get(CONF_INITIAL)
if from_yaml:
self._editable = False
- self.entity_id = ENTITY_ID_FORMAT.format(self.unique_id)
+ self.entity_id = f"{DOMAIN}.{self.unique_id}"
@property
def should_poll(self):
diff --git a/homeassistant/components/input_datetime/__init__.py b/homeassistant/components/input_datetime/__init__.py
index 371e0dea185..575f607dadd 100644
--- a/homeassistant/components/input_datetime/__init__.py
+++ b/homeassistant/components/input_datetime/__init__.py
@@ -27,7 +27,6 @@ from homeassistant.util import dt as dt_util
_LOGGER = logging.getLogger(__name__)
DOMAIN = "input_datetime"
-ENTITY_ID_FORMAT = DOMAIN + ".{}"
CONF_HAS_DATE = "has_date"
CONF_HAS_TIME = "has_time"
@@ -219,7 +218,7 @@ class InputDatetime(RestoreEntity):
def from_yaml(cls, config: typing.Dict) -> "InputDatetime":
"""Return entity instance initialized from yaml storage."""
input_dt = cls(config)
- input_dt.entity_id = ENTITY_ID_FORMAT.format(config[CONF_ID])
+ input_dt.entity_id = f"{DOMAIN}.{config[CONF_ID]}"
input_dt.editable = False
return input_dt
diff --git a/homeassistant/components/input_number/__init__.py b/homeassistant/components/input_number/__init__.py
index eb781baf2ca..8ec26ea3956 100644
--- a/homeassistant/components/input_number/__init__.py
+++ b/homeassistant/components/input_number/__init__.py
@@ -26,7 +26,6 @@ from homeassistant.helpers.typing import ConfigType, HomeAssistantType, ServiceC
_LOGGER = logging.getLogger(__name__)
DOMAIN = "input_number"
-ENTITY_ID_FORMAT = DOMAIN + ".{}"
CONF_INITIAL = "initial"
CONF_MIN = "min"
@@ -209,7 +208,7 @@ class InputNumber(RestoreEntity):
def from_yaml(cls, config: typing.Dict) -> "InputNumber":
"""Return entity instance initialized from yaml storage."""
input_num = cls(config)
- input_num.entity_id = ENTITY_ID_FORMAT.format(config[CONF_ID])
+ input_num.entity_id = f"{DOMAIN}.{config[CONF_ID]}"
input_num.editable = False
return input_num
diff --git a/homeassistant/components/input_select/__init__.py b/homeassistant/components/input_select/__init__.py
index 6044375d8a8..9269dc3a7f9 100644
--- a/homeassistant/components/input_select/__init__.py
+++ b/homeassistant/components/input_select/__init__.py
@@ -23,7 +23,6 @@ from homeassistant.helpers.typing import ConfigType, HomeAssistantType, ServiceC
_LOGGER = logging.getLogger(__name__)
DOMAIN = "input_select"
-ENTITY_ID_FORMAT = DOMAIN + ".{}"
CONF_INITIAL = "initial"
CONF_OPTIONS = "options"
@@ -58,9 +57,7 @@ def _cv_input_select(cfg):
initial = cfg.get(CONF_INITIAL)
if initial is not None and initial not in options:
raise vol.Invalid(
- 'initial state "{}" is not part of the options: {}'.format(
- initial, ",".join(options)
- )
+ f"initial state {initial} is not part of the options: {','.join(options)}"
)
return cfg
@@ -201,7 +198,7 @@ class InputSelect(RestoreEntity):
def from_yaml(cls, config: typing.Dict) -> "InputSelect":
"""Return entity instance initialized from yaml storage."""
input_select = cls(config)
- input_select.entity_id = ENTITY_ID_FORMAT.format(config[CONF_ID])
+ input_select.entity_id = f"{DOMAIN}.{config[CONF_ID]}"
input_select.editable = False
return input_select
diff --git a/homeassistant/components/input_text/__init__.py b/homeassistant/components/input_text/__init__.py
index bdb3e8a4bc9..692a0101249 100644
--- a/homeassistant/components/input_text/__init__.py
+++ b/homeassistant/components/input_text/__init__.py
@@ -26,7 +26,6 @@ from homeassistant.helpers.typing import ConfigType, HomeAssistantType, ServiceC
_LOGGER = logging.getLogger(__name__)
DOMAIN = "input_text"
-ENTITY_ID_FORMAT = DOMAIN + ".{}"
CONF_INITIAL = "initial"
CONF_MIN = "min"
@@ -212,7 +211,7 @@ class InputText(RestoreEntity):
**config,
}
input_text = cls(config)
- input_text.entity_id = ENTITY_ID_FORMAT.format(config[CONF_ID])
+ input_text.entity_id = f"{DOMAIN}.{config[CONF_ID]}"
input_text.editable = False
return input_text
diff --git a/homeassistant/components/insteon/utils.py b/homeassistant/components/insteon/utils.py
index f195a458477..339189d3564 100644
--- a/homeassistant/components/insteon/utils.py
+++ b/homeassistant/components/insteon/utils.py
@@ -189,13 +189,13 @@ def async_register_services(hass, config, insteon_modem):
)
hass.services.async_register(DOMAIN, SRV_PRINT_IM_ALDB, print_im_aldb, schema=None)
hass.services.async_register(
- DOMAIN, SRV_X10_ALL_UNITS_OFF, x10_all_units_off, schema=X10_HOUSECODE_SCHEMA,
+ DOMAIN, SRV_X10_ALL_UNITS_OFF, x10_all_units_off, schema=X10_HOUSECODE_SCHEMA
)
hass.services.async_register(
- DOMAIN, SRV_X10_ALL_LIGHTS_OFF, x10_all_lights_off, schema=X10_HOUSECODE_SCHEMA,
+ DOMAIN, SRV_X10_ALL_LIGHTS_OFF, x10_all_lights_off, schema=X10_HOUSECODE_SCHEMA
)
hass.services.async_register(
- DOMAIN, SRV_X10_ALL_LIGHTS_ON, x10_all_lights_on, schema=X10_HOUSECODE_SCHEMA,
+ DOMAIN, SRV_X10_ALL_LIGHTS_ON, x10_all_lights_on, schema=X10_HOUSECODE_SCHEMA
)
hass.services.async_register(
DOMAIN, SRV_SCENE_ON, scene_on, schema=TRIGGER_SCENE_SCHEMA
@@ -223,17 +223,9 @@ def print_aldb_to_log(aldb):
in_use = "Y" if rec.control_flags.is_in_use else "N"
mode = "C" if rec.control_flags.is_controller else "R"
hwm = "Y" if rec.control_flags.is_high_water_mark else "N"
- _LOGGER.info(
- " {:04x} {:s} {:s} {:s} {:3d} {:s}"
- " {:3d} {:3d} {:3d}".format(
- rec.mem_addr,
- in_use,
- mode,
- hwm,
- rec.group,
- rec.address.human,
- rec.data1,
- rec.data2,
- rec.data3,
- )
+ log_msg = (
+ f" {rec.mem_addr:04x} {in_use:s} {mode:s} {hwm:s} "
+ f"{rec.group:3d} {rec.address.human:s} {rec.data1:3d} "
+ f"{rec.data2:3d} {rec.data3:3d}"
)
+ _LOGGER.info(log_msg)
diff --git a/homeassistant/components/integration/sensor.py b/homeassistant/components/integration/sensor.py
index dea7a5083dc..57ec6fefe29 100644
--- a/homeassistant/components/integration/sensor.py
+++ b/homeassistant/components/integration/sensor.py
@@ -105,8 +105,8 @@ class IntegrationSensor(RestoreEntity):
self._name = name if name is not None else f"{source_entity} integral"
if unit_of_measurement is None:
- self._unit_template = "{}{}{}".format(
- "" if unit_prefix is None else unit_prefix, "{}", unit_time
+ self._unit_template = (
+ f"{'' if unit_prefix is None else unit_prefix}{{}}{unit_time}"
)
# we postpone the definition of unit_of_measurement to later
self._unit_of_measurement = None
diff --git a/homeassistant/components/ios/notify.py b/homeassistant/components/ios/notify.py
index 63ed6a6ee26..62dd72973da 100644
--- a/homeassistant/components/ios/notify.py
+++ b/homeassistant/components/ios/notify.py
@@ -92,8 +92,8 @@ class iOSNotificationService(BaseNotificationService):
if req.status_code != 201:
fallback_error = req.json().get("errorMessage", "Unknown error")
- fallback_message = "Internal server error, please try again later: {}".format(
- fallback_error
+ fallback_message = (
+ f"Internal server error, please try again later: {fallback_error}"
)
message = req.json().get("message", fallback_message)
if req.status_code == 429:
diff --git a/homeassistant/components/ios/sensor.py b/homeassistant/components/ios/sensor.py
index 47c54c3face..85a0a81fdf3 100644
--- a/homeassistant/components/ios/sensor.py
+++ b/homeassistant/components/ios/sensor.py
@@ -30,7 +30,7 @@ class IOSSensor(Entity):
def __init__(self, sensor_type, device_name, device):
"""Initialize the sensor."""
self._device_name = device_name
- self._name = "{} {}".format(device_name, SENSOR_TYPES[sensor_type][0])
+ self._name = f"{device_name} {SENSOR_TYPES[sensor_type][0]}"
self._device = device
self.type = sensor_type
self._state = None
@@ -56,7 +56,7 @@ class IOSSensor(Entity):
def name(self):
"""Return the name of the iOS sensor."""
device_name = self._device[ios.ATTR_DEVICE][ios.ATTR_DEVICE_NAME]
- return "{} {}".format(device_name, SENSOR_TYPES[self.type][0])
+ return f"{device_name} {SENSOR_TYPES[self.type][0]}"
@property
def state(self):
diff --git a/homeassistant/components/iperf3/sensor.py b/homeassistant/components/iperf3/sensor.py
index b298d356df8..70a15a0dac5 100644
--- a/homeassistant/components/iperf3/sensor.py
+++ b/homeassistant/components/iperf3/sensor.py
@@ -28,7 +28,7 @@ class Iperf3Sensor(RestoreEntity):
def __init__(self, iperf3_data, sensor_type):
"""Initialize the sensor."""
- self._name = "{} {}".format(SENSOR_TYPES[sensor_type][0], iperf3_data.host)
+ self._name = f"{SENSOR_TYPES[sensor_type][0]} {iperf3_data.host}"
self._state = None
self._sensor_type = sensor_type
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
diff --git a/homeassistant/components/ipma/const.py b/homeassistant/components/ipma/const.py
index e68c12de13c..04064db2b88 100644
--- a/homeassistant/components/ipma/const.py
+++ b/homeassistant/components/ipma/const.py
@@ -7,7 +7,6 @@ DOMAIN = "ipma"
HOME_LOCATION_NAME = "Home"
-ENTITY_ID_SENSOR_FORMAT = WEATHER_DOMAIN + ".ipma_{}"
-ENTITY_ID_SENSOR_FORMAT_HOME = ENTITY_ID_SENSOR_FORMAT.format(HOME_LOCATION_NAME)
+ENTITY_ID_SENSOR_FORMAT_HOME = f"{WEATHER_DOMAIN}.ipma_{HOME_LOCATION_NAME}"
_LOGGER = logging.getLogger(".")
diff --git a/homeassistant/components/iqvia/sensor.py b/homeassistant/components/iqvia/sensor.py
index e093556b810..1aae63a4908 100644
--- a/homeassistant/components/iqvia/sensor.py
+++ b/homeassistant/components/iqvia/sensor.py
@@ -198,6 +198,6 @@ class IndexSensor(IQVIAEntity):
)
elif self._type == TYPE_DISEASE_TODAY:
for attrs in period["Triggers"]:
- self._attrs["{0}_index".format(attrs["Name"].lower())] = attrs["Index"]
+ self._attrs[f"{attrs['Name'].lower()}_index"] = attrs["Index"]
self._state = period["Index"]
diff --git a/homeassistant/components/islamic_prayer_times/sensor.py b/homeassistant/components/islamic_prayer_times/sensor.py
index 3f7de535407..076718e83a2 100644
--- a/homeassistant/components/islamic_prayer_times/sensor.py
+++ b/homeassistant/components/islamic_prayer_times/sensor.py
@@ -97,7 +97,7 @@ async def schedule_future_update(hass, sensors, midnight_time, prayer_times_data
now = dt_util.as_local(dt_util.now())
today = now.date()
- midnight_dt_str = "{}::{}".format(str(today), midnight_time)
+ midnight_dt_str = f"{today}::{midnight_time}"
midnight_dt = datetime.strptime(midnight_dt_str, "%Y-%m-%d::%H:%M")
if now > dt_util.as_local(midnight_dt):
@@ -166,12 +166,10 @@ class IslamicPrayerTimesData:
class IslamicPrayerTimeSensor(Entity):
"""Representation of an Islamic prayer time sensor."""
- ENTITY_ID_FORMAT = "sensor.islamic_prayer_time_{}"
-
def __init__(self, sensor_type, prayer_times_data):
"""Initialize the Islamic prayer time sensor."""
self.sensor_type = sensor_type
- self.entity_id = self.ENTITY_ID_FORMAT.format(self.sensor_type)
+ self.entity_id = f"sensor.islamic_prayer_time_{self.sensor_type}"
self.prayer_times_data = prayer_times_data
self._name = self.sensor_type.capitalize()
self._device_class = DEVICE_CLASS_TIMESTAMP
@@ -208,7 +206,7 @@ class IslamicPrayerTimeSensor(Entity):
def get_prayer_time_as_dt(prayer_time):
"""Create a datetime object for the respective prayer time."""
today = datetime.today().strftime("%Y-%m-%d")
- date_time_str = "{} {}".format(str(today), prayer_time)
+ date_time_str = f"{today} {prayer_time}"
pt_dt = dt_util.parse_datetime(date_time_str)
return pt_dt
diff --git a/homeassistant/components/isy994/__init__.py b/homeassistant/components/isy994/__init__.py
index c1474334a8e..3cffbdb1214 100644
--- a/homeassistant/components/isy994/__init__.py
+++ b/homeassistant/components/isy994/__init__.py
@@ -529,5 +529,5 @@ class ISYDevice(Entity):
attr = {}
if hasattr(self._node, "aux_properties"):
for name, val in self._node.aux_properties.items():
- attr[name] = "{} {}".format(val.get("value"), val.get("uom"))
+ attr[name] = f"{val.get('value')} {val.get('uom')}"
return attr
diff --git a/homeassistant/components/isy994/binary_sensor.py b/homeassistant/components/isy994/binary_sensor.py
index 7e69feb2f70..917dedd5c53 100644
--- a/homeassistant/components/isy994/binary_sensor.py
+++ b/homeassistant/components/isy994/binary_sensor.py
@@ -84,7 +84,7 @@ def _detect_device_type(node) -> str:
split_type = device_type.split(".")
for device_class, ids in ISY_DEVICE_TYPES.items():
- if "{}.{}".format(split_type[0], split_type[1]) in ids:
+ if f"{split_type[0]}.{split_type[1]}" in ids:
return device_class
return None
diff --git a/homeassistant/components/izone/climate.py b/homeassistant/components/izone/climate.py
index b80dfc2542f..20673312fa7 100644
--- a/homeassistant/components/izone/climate.py
+++ b/homeassistant/components/izone/climate.py
@@ -437,7 +437,7 @@ class ZoneDevice(ClimateDevice):
@property
def unique_id(self):
"""Return the ID of the controller device."""
- return "{}_z{}".format(self._controller.unique_id, self._zone.index + 1)
+ return f"{self._controller.unique_id}_z{self._zone.index + 1}"
@property
def name(self) -> str:
diff --git a/homeassistant/components/juicenet/__init__.py b/homeassistant/components/juicenet/__init__.py
index 55bf91ac398..969e193bac8 100644
--- a/homeassistant/components/juicenet/__init__.py
+++ b/homeassistant/components/juicenet/__init__.py
@@ -65,4 +65,4 @@ class JuicenetDevice(Entity):
@property
def unique_id(self):
"""Return a unique ID."""
- return "{}-{}".format(self.device.id(), self.type)
+ return f"{self.device.id()}-{self.type}"
diff --git a/homeassistant/components/juicenet/sensor.py b/homeassistant/components/juicenet/sensor.py
index 67a04d39556..6ddb8279811 100644
--- a/homeassistant/components/juicenet/sensor.py
+++ b/homeassistant/components/juicenet/sensor.py
@@ -43,7 +43,7 @@ class JuicenetSensorDevice(JuicenetDevice, Entity):
@property
def name(self):
"""Return the name of the device."""
- return "{} {}".format(self.device.name(), self._name)
+ return f"{self.device.name()} {self._name}"
@property
def icon(self):
diff --git a/homeassistant/components/knx/__init__.py b/homeassistant/components/knx/__init__.py
index 5640106eefa..edd42678a1f 100644
--- a/homeassistant/components/knx/__init__.py
+++ b/homeassistant/components/knx/__init__.py
@@ -102,7 +102,7 @@ async def async_setup(hass, config):
except XKNXException as ex:
_LOGGER.warning("Can't connect to KNX interface: %s", ex)
hass.components.persistent_notification.async_create(
- "Can't connect to KNX interface:
{0}".format(ex), title="KNX"
+ f"Can't connect to KNX interface:
{ex}", title="KNX"
)
for component, discovery_type in (
@@ -291,7 +291,7 @@ class KNXAutomation:
"""Initialize Automation class."""
self.hass = hass
self.device = device
- script_name = "{} turn ON script".format(device.get_name())
+ script_name = f"{device.get_name()} turn ON script"
self.script = Script(hass, action, script_name)
self.action = ActionCallback(
diff --git a/homeassistant/components/kodi/media_player.py b/homeassistant/components/kodi/media_player.py
index f326ba60375..4fd86d078a0 100644
--- a/homeassistant/components/kodi/media_player.py
+++ b/homeassistant/components/kodi/media_player.py
@@ -183,7 +183,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
encryption = config.get(CONF_PROXY_SSL)
websocket = config.get(CONF_ENABLE_WEBSOCKET)
else:
- name = "{} ({})".format(DEFAULT_NAME, discovery_info.get("hostname"))
+ name = f"{DEFAULT_NAME} ({discovery_info.get('hostname')})"
host = discovery_info.get("host")
port = discovery_info.get("port")
tcp_port = DEFAULT_TCP_PORT
@@ -286,9 +286,7 @@ class KodiDevice(MediaPlayerDevice):
ws_protocol = "wss" if encryption else "ws"
self._http_url = f"{http_protocol}://{host}:{port}/jsonrpc"
- self._image_url = "{}://{}{}:{}/image".format(
- http_protocol, image_auth_string, host, port
- )
+ self._image_url = f"{http_protocol}://{image_auth_string}{host}:{port}/image"
self._ws_url = f"{ws_protocol}://{host}:{tcp_port}/jsonrpc"
self._http_server = jsonrpc_async.Server(self._http_url, **kwargs)
@@ -577,7 +575,7 @@ class KodiDevice(MediaPlayerDevice):
url_components = urllib.parse.urlparse(thumbnail)
if url_components.scheme == "image":
- return "{}/{}".format(self._image_url, urllib.parse.quote_plus(thumbnail))
+ return f"{self._image_url}/{urllib.parse.quote_plus(thumbnail)}"
@property
def media_title(self):
diff --git a/homeassistant/components/kodi/notify.py b/homeassistant/components/kodi/notify.py
index aa3fe0610a7..e431763b8bd 100644
--- a/homeassistant/components/kodi/notify.py
+++ b/homeassistant/components/kodi/notify.py
@@ -44,7 +44,7 @@ ATTR_DISPLAYTIME = "displaytime"
async def async_get_service(hass, config, discovery_info=None):
"""Return the notify service."""
- url = "{}:{}".format(config.get(CONF_HOST), config.get(CONF_PORT))
+ url = f"{config.get(CONF_HOST)}:{config.get(CONF_PORT)}"
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
diff --git a/homeassistant/components/konnected/binary_sensor.py b/homeassistant/components/konnected/binary_sensor.py
index dc4dae7787f..50f897e3a85 100644
--- a/homeassistant/components/konnected/binary_sensor.py
+++ b/homeassistant/components/konnected/binary_sensor.py
@@ -13,7 +13,7 @@ from homeassistant.const import (
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
-from .const import DOMAIN as KONNECTED_DOMAIN, SIGNAL_SENSOR_UPDATE
+from .const import DOMAIN as KONNECTED_DOMAIN
_LOGGER = logging.getLogger(__name__)
@@ -80,7 +80,7 @@ class KonnectedBinarySensor(BinarySensorDevice):
"""Store entity_id and register state change callback."""
self._data[ATTR_ENTITY_ID] = self.entity_id
async_dispatcher_connect(
- self.hass, SIGNAL_SENSOR_UPDATE.format(self.entity_id), self.async_set_state
+ self.hass, f"konnected.{self.entity_id}.update", self.async_set_state
)
@callback
diff --git a/homeassistant/components/konnected/const.py b/homeassistant/components/konnected/const.py
index d6819dcf71f..7cb0ffc5f80 100644
--- a/homeassistant/components/konnected/const.py
+++ b/homeassistant/components/konnected/const.py
@@ -46,5 +46,4 @@ ZONE_TO_PIN = {zone: pin for pin, zone in PIN_TO_ZONE.items()}
ENDPOINT_ROOT = "/api/konnected"
UPDATE_ENDPOINT = ENDPOINT_ROOT + r"/device/{device_id:[a-zA-Z0-9]+}"
-SIGNAL_SENSOR_UPDATE = "konnected.{}.update"
SIGNAL_DS18B20_NEW = "konnected.ds18b20.new"
diff --git a/homeassistant/components/konnected/handlers.py b/homeassistant/components/konnected/handlers.py
index a8914853e84..923e5d63899 100644
--- a/homeassistant/components/konnected/handlers.py
+++ b/homeassistant/components/konnected/handlers.py
@@ -10,7 +10,7 @@ from homeassistant.const import (
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.util import decorator
-from .const import CONF_INVERSE, SIGNAL_DS18B20_NEW, SIGNAL_SENSOR_UPDATE
+from .const import CONF_INVERSE, SIGNAL_DS18B20_NEW
_LOGGER = logging.getLogger(__name__)
HANDLERS = decorator.Registry()
@@ -25,7 +25,7 @@ async def async_handle_state_update(hass, context, msg):
if context.get(CONF_INVERSE):
state = not state
- async_dispatcher_send(hass, SIGNAL_SENSOR_UPDATE.format(entity_id), state)
+ async_dispatcher_send(hass, f"konnected.{entity_id}.update", state)
@HANDLERS.register("temp")
@@ -34,7 +34,7 @@ async def async_handle_temp_update(hass, context, msg):
_LOGGER.debug("[temp handler] context: %s msg: %s", context, msg)
entity_id, temp = context.get(DEVICE_CLASS_TEMPERATURE), msg.get("temp")
if entity_id:
- async_dispatcher_send(hass, SIGNAL_SENSOR_UPDATE.format(entity_id), temp)
+ async_dispatcher_send(hass, f"konnected.{entity_id}.update", temp)
@HANDLERS.register("humi")
@@ -43,7 +43,7 @@ async def async_handle_humi_update(hass, context, msg):
_LOGGER.debug("[humi handler] context: %s msg: %s", context, msg)
entity_id, humi = context.get(DEVICE_CLASS_HUMIDITY), msg.get("humi")
if entity_id:
- async_dispatcher_send(hass, SIGNAL_SENSOR_UPDATE.format(entity_id), humi)
+ async_dispatcher_send(hass, f"konnected.{entity_id}.update", humi)
@HANDLERS.register("addr")
@@ -53,7 +53,7 @@ async def async_handle_addr_update(hass, context, msg):
addr, temp = msg.get("addr"), msg.get("temp")
entity_id = context.get(addr)
if entity_id:
- async_dispatcher_send(hass, SIGNAL_SENSOR_UPDATE.format(entity_id), temp)
+ async_dispatcher_send(hass, f"konnected.{entity_id}.update", temp)
else:
msg["device_id"] = context.get("device_id")
msg["temperature"] = temp
diff --git a/homeassistant/components/konnected/panel.py b/homeassistant/components/konnected/panel.py
index 2668a382ccc..783aa78b8b1 100644
--- a/homeassistant/components/konnected/panel.py
+++ b/homeassistant/components/konnected/panel.py
@@ -39,7 +39,6 @@ from .const import (
CONF_REPEAT,
DOMAIN,
ENDPOINT_ROOT,
- SIGNAL_SENSOR_UPDATE,
STATE_LOW,
ZONE_TO_PIN,
)
@@ -290,9 +289,7 @@ class AlarmPanel:
if sensor_config.get(CONF_INVERSE):
state = not state
- async_dispatcher_send(
- self.hass, SIGNAL_SENSOR_UPDATE.format(entity_id), state
- )
+ async_dispatcher_send(self.hass, f"konnected.{entity_id}.update", state)
@callback
def async_desired_settings_payload(self):
diff --git a/homeassistant/components/konnected/sensor.py b/homeassistant/components/konnected/sensor.py
index d189ac8809a..4fa238166f8 100644
--- a/homeassistant/components/konnected/sensor.py
+++ b/homeassistant/components/konnected/sensor.py
@@ -15,7 +15,7 @@ from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import Entity
-from .const import DOMAIN as KONNECTED_DOMAIN, SIGNAL_DS18B20_NEW, SIGNAL_SENSOR_UPDATE
+from .const import DOMAIN as KONNECTED_DOMAIN, SIGNAL_DS18B20_NEW
_LOGGER = logging.getLogger(__name__)
@@ -84,9 +84,7 @@ class KonnectedSensor(Entity):
self._type = sensor_type
self._zone_num = self._data.get(CONF_ZONE)
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
- self._unique_id = addr or "{}-{}-{}".format(
- device_id, self._zone_num, sensor_type
- )
+ self._unique_id = addr or f"{device_id}-{self._zone_num}-{sensor_type}"
# set initial state if known at initialization
self._state = initial_state
@@ -130,7 +128,7 @@ class KonnectedSensor(Entity):
entity_id_key = self._addr or self._type
self._data[entity_id_key] = self.entity_id
async_dispatcher_connect(
- self.hass, SIGNAL_SENSOR_UPDATE.format(self.entity_id), self.async_set_state
+ self.hass, f"konnected.{self.entity_id}.update", self.async_set_state
)
@callback
diff --git a/homeassistant/components/konnected/switch.py b/homeassistant/components/konnected/switch.py
index d16051eb8da..b8ddec20440 100644
--- a/homeassistant/components/konnected/switch.py
+++ b/homeassistant/components/konnected/switch.py
@@ -48,8 +48,9 @@ class KonnectedSwitch(ToggleEntity):
self._repeat = self._data.get(CONF_REPEAT)
self._state = self._boolean_state(self._data.get(ATTR_STATE))
self._name = self._data.get(CONF_NAME)
- self._unique_id = "{}-{}-{}-{}-{}".format(
- device_id, self._zone_num, self._momentary, self._pause, self._repeat
+ self._unique_id = (
+ f"{device_id}-{self._zone_num}-{self._momentary}-"
+ f"{self._pause}-{self._repeat}"
)
@property
diff --git a/homeassistant/components/lastfm/sensor.py b/homeassistant/components/lastfm/sensor.py
index 1a5b7a56e8e..80a72f1d6fd 100644
--- a/homeassistant/components/lastfm/sensor.py
+++ b/homeassistant/components/lastfm/sensor.py
@@ -89,7 +89,7 @@ class LastfmSensor(Entity):
top = self._user.get_top_tracks(limit=1)[0]
toptitle = re.search("', '(.+?)',", str(top))
topartist = re.search("'(.+?)',", str(top))
- self._topplayed = "{} - {}".format(topartist.group(1), toptitle.group(1))
+ self._topplayed = f"{topartist.group(1)} - {toptitle.group(1)}"
if self._user.get_now_playing() is None:
self._state = "Not Scrobbling"
return
diff --git a/homeassistant/components/lcn/const.py b/homeassistant/components/lcn/const.py
index c49319abf42..ff7de1987da 100644
--- a/homeassistant/components/lcn/const.py
+++ b/homeassistant/components/lcn/const.py
@@ -92,9 +92,7 @@ BINSENSOR_PORTS = [
"BINSENSOR8",
]
-KEYS = [
- "{:s}{:d}".format(t[0], t[1]) for t in product(["A", "B", "C", "D"], range(1, 9))
-]
+KEYS = [f"{t[0]:s}{t[1]:d}" for t in product(["A", "B", "C", "D"], range(1, 9))]
VARIABLES = [
"VAR1ORTVAR",
diff --git a/homeassistant/components/life360/__init__.py b/homeassistant/components/life360/__init__.py
index a0c40a59a46..50117c210a2 100644
--- a/homeassistant/components/life360/__init__.py
+++ b/homeassistant/components/life360/__init__.py
@@ -67,9 +67,7 @@ def _thresholds(config):
if error_threshold and warning_threshold:
if error_threshold <= warning_threshold:
raise vol.Invalid(
- "{} must be larger than {}".format(
- CONF_ERROR_THRESHOLD, CONF_WARNING_THRESHOLD
- )
+ f"{CONF_ERROR_THRESHOLD} must be larger than {CONF_WARNING_THRESHOLD}"
)
elif not error_threshold and warning_threshold:
config[CONF_ERROR_THRESHOLD] = warning_threshold + 1
diff --git a/homeassistant/components/life360/device_tracker.py b/homeassistant/components/life360/device_tracker.py
index 6f4255735e0..b6cd67c2627 100644
--- a/homeassistant/components/life360/device_tracker.py
+++ b/homeassistant/components/life360/device_tracker.py
@@ -72,7 +72,7 @@ def _include_name(filter_dict, name):
def _exc_msg(exc):
- return "{}: {}".format(exc.__class__.__name__, str(exc))
+ return f"{exc.__class__.__name__}: {exc}"
def _dump_filter(filter_dict, desc, func=lambda x: x):
@@ -253,7 +253,7 @@ class Life360Scanner:
msg = f"Updating {dev_id}"
if prev_seen:
- msg += "; Time since last update: {}".format(last_seen - prev_seen)
+ msg += f"; Time since last update: {last_seen - prev_seen}"
_LOGGER.debug(msg)
if self._max_gps_accuracy is not None and gps_accuracy > self._max_gps_accuracy:
@@ -402,10 +402,10 @@ class Life360Scanner:
places = api.get_circle_places(circle_id)
place_data = "Circle's Places:"
for place in places:
- place_data += "\n- name: {}".format(place["name"])
- place_data += "\n latitude: {}".format(place["latitude"])
- place_data += "\n longitude: {}".format(place["longitude"])
- place_data += "\n radius: {}".format(place["radius"])
+ place_data += f"\n- name: {place['name']}"
+ place_data += f"\n latitude: {place['latitude']}"
+ place_data += f"\n longitude: {place['longitude']}"
+ place_data += f"\n radius: {place['radius']}"
if not places:
place_data += " None"
_LOGGER.debug(place_data)
diff --git a/homeassistant/components/lifx_cloud/scene.py b/homeassistant/components/lifx_cloud/scene.py
index 4068ff20fe2..08e044a46e0 100644
--- a/homeassistant/components/lifx_cloud/scene.py
+++ b/homeassistant/components/lifx_cloud/scene.py
@@ -14,7 +14,6 @@ import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
-LIFX_API_URL = "https://api.lifx.com/v1/{0}"
DEFAULT_TIMEOUT = 10
PLATFORM_SCHEMA = vol.Schema(
@@ -33,7 +32,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
headers = {AUTHORIZATION: f"Bearer {token}"}
- url = LIFX_API_URL.format("scenes")
+ url = "https://api.lifx.com/v1/scenes"
try:
httpsession = async_get_clientsession(hass)
@@ -78,7 +77,7 @@ class LifxCloudScene(Scene):
async def async_activate(self):
"""Activate the scene."""
- url = LIFX_API_URL.format("scenes/scene_id:%s/activate" % self._uuid)
+ url = f"https://api.lifx.com/v1/scenes/scene_id:{self._uuid}/activate"
try:
httpsession = async_get_clientsession(self.hass)
diff --git a/homeassistant/components/light/intent.py b/homeassistant/components/light/intent.py
index c172ac1330a..58f74d8a422 100644
--- a/homeassistant/components/light/intent.py
+++ b/homeassistant/components/light/intent.py
@@ -51,14 +51,12 @@ class SetIntentHandler(intent.IntentHandler):
service_data[ATTR_RGB_COLOR] = slots["color"]["value"]
# Use original passed in value of the color because we don't have
# human readable names for that internally.
- speech_parts.append(
- "the color {}".format(intent_obj.slots["color"]["value"])
- )
+ speech_parts.append(f"the color {intent_obj.slots['color']['value']}")
if "brightness" in slots:
intent.async_test_feature(state, SUPPORT_BRIGHTNESS, "changing brightness")
service_data[ATTR_BRIGHTNESS_PCT] = slots["brightness"]["value"]
- speech_parts.append("{}% brightness".format(slots["brightness"]["value"]))
+ speech_parts.append(f"{slots['brightness']['value']}% brightness")
await hass.services.async_call(
DOMAIN, SERVICE_TURN_ON, service_data, context=intent_obj.context
diff --git a/homeassistant/components/locative/__init__.py b/homeassistant/components/locative/__init__.py
index ea36aa9f7fb..978f50b0ffd 100644
--- a/homeassistant/components/locative/__init__.py
+++ b/homeassistant/components/locative/__init__.py
@@ -93,9 +93,7 @@ async def handle_webhook(hass, webhook_id, request):
# before the previous zone was exited. The enter message will
# be sent first, then the exit message will be sent second.
return web.Response(
- text="Ignoring exit from {} (already in {})".format(
- location_name, current_state
- ),
+ text=f"Ignoring exit from {location_name} (already in {current_state})",
status=HTTP_OK,
)
diff --git a/homeassistant/components/lockitron/lock.py b/homeassistant/components/lockitron/lock.py
index 5840c7f5537..8ff8f430355 100644
--- a/homeassistant/components/lockitron/lock.py
+++ b/homeassistant/components/lockitron/lock.py
@@ -16,15 +16,15 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{vol.Required(CONF_ACCESS_TOKEN): cv.string, vol.Required(CONF_ID): cv.string}
)
BASE_URL = "https://api.lockitron.com"
-API_STATE_URL = BASE_URL + "/v2/locks/{}?access_token={}"
-API_ACTION_URL = BASE_URL + "/v2/locks/{}?access_token={}&state={}"
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Lockitron platform."""
access_token = config.get(CONF_ACCESS_TOKEN)
device_id = config.get(CONF_ID)
- response = requests.get(API_STATE_URL.format(device_id, access_token), timeout=5)
+ response = requests.get(
+ f"{BASE_URL}/v2/locks/{device_id}?access_token={access_token}", timeout=5
+ )
if response.status_code == 200:
add_entities([Lockitron(response.json()["state"], access_token, device_id)])
else:
@@ -64,7 +64,8 @@ class Lockitron(LockDevice):
def update(self):
"""Update the internal state of the device."""
response = requests.get(
- API_STATE_URL.format(self.device_id, self.access_token), timeout=5
+ f"{BASE_URL}/v2/locks/{self.device_id}?access_token={self.access_token}",
+ timeout=5,
)
if response.status_code == 200:
self._state = response.json()["state"]
@@ -74,7 +75,7 @@ class Lockitron(LockDevice):
def do_change_request(self, requested_state):
"""Execute the change request and pull out the new state."""
response = requests.put(
- API_ACTION_URL.format(self.device_id, self.access_token, requested_state),
+ f"{BASE_URL}/v2/locks/{self.device_id}?access_token={self.access_token}&state={requested_state}",
timeout=5,
)
if response.status_code == 200:
diff --git a/homeassistant/components/logbook/__init__.py b/homeassistant/components/logbook/__init__.py
index ac45a636bf7..266ff3601eb 100644
--- a/homeassistant/components/logbook/__init__.py
+++ b/homeassistant/components/logbook/__init__.py
@@ -318,13 +318,9 @@ def humanify(hass, events):
if entity_id:
state = hass.states.get(entity_id)
name = state.name if state else entity_id
- message = "send command {}/{} for {}".format(
- data["request"]["namespace"], data["request"]["name"], name
- )
+ message = f"send command {data['request']['namespace']}/{data['request']['name']} for {name}"
else:
- message = "send command {}/{}".format(
- data["request"]["namespace"], data["request"]["name"]
- )
+ message = f"send command {data['request']['namespace']}/{data['request']['name']}"
yield {
"when": event.time_fired,
@@ -342,9 +338,7 @@ def humanify(hass, events):
value = data.get(ATTR_VALUE)
value_msg = f" to {value}" if value else ""
- message = "send command {}{} for {}".format(
- data[ATTR_SERVICE], value_msg, data[ATTR_DISPLAY_NAME]
- )
+ message = f"send command {data[ATTR_SERVICE]}{value_msg} for {data[ATTR_DISPLAY_NAME]}"
yield {
"when": event.time_fired,
diff --git a/homeassistant/components/logi_circle/__init__.py b/homeassistant/components/logi_circle/__init__.py
index b77f17101a8..0a6d471889f 100644
--- a/homeassistant/components/logi_circle/__init__.py
+++ b/homeassistant/components/logi_circle/__init__.py
@@ -130,9 +130,10 @@ async def async_setup_entry(hass, entry):
if not logi_circle.authorized:
hass.components.persistent_notification.create(
- "Error: The cached access tokens are missing from {}.
"
- "Please unload then re-add the Logi Circle integration to resolve."
- "".format(DEFAULT_CACHEDB),
+ (
+ f"Error: The cached access tokens are missing from {DEFAULT_CACHEDB}.
"
+ f"Please unload then re-add the Logi Circle integration to resolve."
+ ),
title=NOTIFICATION_TITLE,
notification_id=NOTIFICATION_ID,
)
@@ -158,18 +159,14 @@ async def async_setup_entry(hass, entry):
# string, so we'll handle it separately.
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."
- "".format(err),
+ f"Error: {err}
You will need to restart hass after fixing.",
title=NOTIFICATION_TITLE,
notification_id=NOTIFICATION_ID,
)
return False
except ClientResponseError as 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,
)
diff --git a/homeassistant/components/logi_circle/sensor.py b/homeassistant/components/logi_circle/sensor.py
index fc5ad7155b4..4a5fedaf57a 100644
--- a/homeassistant/components/logi_circle/sensor.py
+++ b/homeassistant/components/logi_circle/sensor.py
@@ -50,10 +50,8 @@ class LogiSensor(Entity):
self._sensor_type = sensor_type
self._camera = camera
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]
- )
+ self._icon = f"mdi:{SENSOR_TYPES.get(self._sensor_type)[2]}"
+ self._name = f"{self._camera.name} {SENSOR_TYPES.get(self._sensor_type)[0]}"
self._activity = {}
self._state = None
self._tz = time_zone
@@ -127,8 +125,8 @@ class LogiSensor(Entity):
last_activity = await self._camera.get_last_activity(force_refresh=True)
if last_activity is not None:
last_activity_time = as_local(last_activity.end_time_utc)
- self._state = "{0:0>2}:{1:0>2}".format(
- last_activity_time.hour, last_activity_time.minute
+ self._state = (
+ f"{last_activity_time.hour:0>2}:{last_activity_time.minute:0>2}"
)
else:
state = getattr(self._camera, self._sensor_type, None)
diff --git a/homeassistant/components/lovelace/dashboard.py b/homeassistant/components/lovelace/dashboard.py
index dcd7a6c4e52..a04a2376c74 100644
--- a/homeassistant/components/lovelace/dashboard.py
+++ b/homeassistant/components/lovelace/dashboard.py
@@ -138,7 +138,7 @@ class LovelaceYAML(LovelaceConfig):
except ConfigNotFound:
return {
"mode": self.mode,
- "error": "{} not found".format(self.path),
+ "error": f"{self.path} not found",
}
return _config_info(self.mode, config)
diff --git a/homeassistant/components/luftdaten/sensor.py b/homeassistant/components/luftdaten/sensor.py
index 6fc48081adc..cfde5bba872 100644
--- a/homeassistant/components/luftdaten/sensor.py
+++ b/homeassistant/components/luftdaten/sensor.py
@@ -80,7 +80,7 @@ class LuftdatenSensor(Entity):
def unique_id(self) -> str:
"""Return a unique, friendly identifier for this entity."""
if self._data is not None:
- return "{0}_{1}".format(self._data["sensor_id"], self.sensor_type)
+ return f"{self._data['sensor_id']}_{self.sensor_type}"
@property
def device_state_attributes(self):
diff --git a/homeassistant/components/lupusec/__init__.py b/homeassistant/components/lupusec/__init__.py
index 60f3a192b07..3ae07bd8105 100644
--- a/homeassistant/components/lupusec/__init__.py
+++ b/homeassistant/components/lupusec/__init__.py
@@ -47,9 +47,7 @@ def setup(hass, config):
_LOGGER.error(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,
)
diff --git a/homeassistant/components/lutron/scene.py b/homeassistant/components/lutron/scene.py
index 3f625a7c28b..4e06c5df626 100644
--- a/homeassistant/components/lutron/scene.py
+++ b/homeassistant/components/lutron/scene.py
@@ -37,6 +37,4 @@ class LutronScene(LutronDevice, Scene):
@property
def name(self):
"""Return the name of the device."""
- return "{} {}: {}".format(
- self._area_name, self._keypad_name, self._lutron_device.name
- )
+ return f"{self._area_name} {self._keypad_name}: {self._lutron_device.name}"
diff --git a/homeassistant/components/lyft/sensor.py b/homeassistant/components/lyft/sensor.py
index d76fe9f0dc5..5e8555f857d 100644
--- a/homeassistant/components/lyft/sensor.py
+++ b/homeassistant/components/lyft/sensor.py
@@ -85,7 +85,7 @@ class LyftSensor(Entity):
self._product_id = product_id
self._product = product
self._sensortype = sensorType
- self._name = "{} {}".format(self._product["display_name"], self._sensortype)
+ self._name = f"{self._product['display_name']} {self._sensortype}"
if "lyft" not in self._name.lower():
self._name = f"Lyft{self._name}"
if self._sensortype == "time":
diff --git a/tests/components/homekit_controller/common.py b/tests/components/homekit_controller/common.py
index f6f2490e48b..7e27d1a970b 100644
--- a/tests/components/homekit_controller/common.py
+++ b/tests/components/homekit_controller/common.py
@@ -166,5 +166,5 @@ async def setup_test_component(hass, setup_accessory, capitalize=False, suffix=N
assert domain, "Cannot map test homekit services to Home Assistant domain"
config_entry, pairing = await setup_test_accessories(hass, [accessory])
- entity = "testdevice" if suffix is None else "testdevice_{}".format(suffix)
+ entity = "testdevice" if suffix is None else f"testdevice_{suffix}"
return Helper(hass, ".".join((domain, entity)), pairing, accessory, config_entry)
diff --git a/tests/components/universal/test_media_player.py b/tests/components/universal/test_media_player.py
index cf985621351..cf3fc8fcb33 100644
--- a/tests/components/universal/test_media_player.py
+++ b/tests/components/universal/test_media_player.py
@@ -184,13 +184,13 @@ class TestMediaPlayer(unittest.TestCase):
self.mock_state_switch_id = switch.ENTITY_ID_FORMAT.format("state")
self.hass.states.set(self.mock_state_switch_id, STATE_OFF)
- self.mock_volume_id = input_number.ENTITY_ID_FORMAT.format("volume_level")
+ self.mock_volume_id = f"{input_number.DOMAIN}.volume_level"
self.hass.states.set(self.mock_volume_id, 0)
- self.mock_source_list_id = input_select.ENTITY_ID_FORMAT.format("source_list")
+ self.mock_source_list_id = f"{input_select.DOMAIN}.source_list"
self.hass.states.set(self.mock_source_list_id, ["dvd", "htpc"])
- self.mock_source_id = input_select.ENTITY_ID_FORMAT.format("source")
+ self.mock_source_id = f"{input_select.DOMAIN}.source"
self.hass.states.set(self.mock_source_id, "dvd")
self.mock_shuffle_switch_id = switch.ENTITY_ID_FORMAT.format("shuffle")