Use literal string interpolation in integrations T-W (f-strings) (#26394)

This commit is contained in:
Franck Nijhof 2019-09-03 21:12:51 +02:00 committed by Pascal Vizeli
parent cde09062c4
commit ef0e9431b6
50 changed files with 128 additions and 132 deletions

View File

@ -124,7 +124,7 @@ def create_climate_device(tado, hass, zone, name, zone_id):
max_temp = float(temperatures["celsius"]["max"]) max_temp = float(temperatures["celsius"]["max"])
step = temperatures["celsius"].get("step", PRECISION_TENTHS) step = temperatures["celsius"].get("step", PRECISION_TENTHS)
data_id = "zone {} {}".format(name, zone_id) data_id = f"zone {name} {zone_id}"
device = TadoClimate( device = TadoClimate(
tado, tado,
name, name,

View File

@ -80,7 +80,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
def create_zone_sensor(tado, zone, name, zone_id, variable): def create_zone_sensor(tado, zone, name, zone_id, variable):
"""Create a zone sensor.""" """Create a zone sensor."""
data_id = "zone {} {}".format(name, zone_id) data_id = f"zone {name} {zone_id}"
tado.add_sensor( tado.add_sensor(
data_id, data_id,
@ -92,7 +92,7 @@ def create_zone_sensor(tado, zone, name, zone_id, variable):
def create_device_sensor(tado, device, name, device_id, variable): def create_device_sensor(tado, device, name, device_id, variable):
"""Create a device sensor.""" """Create a device sensor."""
data_id = "device {} {}".format(name, device_id) data_id = f"device {name} {device_id}"
tado.add_sensor( tado.add_sensor(
data_id, data_id,
@ -118,7 +118,7 @@ class TadoSensor(Entity):
self.zone_id = zone_id self.zone_id = zone_id
self.zone_variable = zone_variable self.zone_variable = zone_variable
self._unique_id = "{} {}".format(zone_variable, zone_id) self._unique_id = f"{zone_variable} {zone_id}"
self._data_id = data_id self._data_id = data_id
self._state = None self._state = None
@ -132,7 +132,7 @@ class TadoSensor(Entity):
@property @property
def name(self): def name(self):
"""Return the name of the sensor.""" """Return the name of the sensor."""
return "{} {}".format(self.zone_name, self.zone_variable) return f"{self.zone_name} {self.zone_variable}"
@property @property
def state(self): def state(self):

View File

@ -45,7 +45,7 @@ class TapsAffSensor(BinarySensorDevice):
@property @property
def name(self): def name(self):
"""Return the name of the sensor.""" """Return the name of the sensor."""
return "{}".format(self._name) return f"{self._name}"
@property @property
def is_on(self): def is_on(self):

View File

@ -32,7 +32,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
host = config.get(CONF_HOST) host = config.get(CONF_HOST)
port = config.get(CONF_PORT) port = config.get(CONF_PORT)
name = config.get(CONF_NAME) name = config.get(CONF_NAME)
url = "http://{}:{}/api/LiveData.xml".format(host, port) url = f"http://{host}:{port}/api/LiveData.xml"
gateway = Ted5000Gateway(url) gateway = Ted5000Gateway(url)

View File

@ -90,7 +90,7 @@ class TekSavvySensor(Entity):
@property @property
def name(self): def name(self):
"""Return the name of the sensor.""" """Return the name of the sensor."""
return "{} {}".format(self.client_name, self._name) return f"{self.client_name} {self._name}"
@property @property
def state(self): def state(self):

View File

@ -554,7 +554,7 @@ class TelegramNotificationService:
def send_message(self, message="", target=None, **kwargs): def send_message(self, message="", target=None, **kwargs):
"""Send a message to one or multiple pre-allowed chat IDs.""" """Send a message to one or multiple pre-allowed chat IDs."""
title = kwargs.get(ATTR_TITLE) title = kwargs.get(ATTR_TITLE)
text = "{}\n{}".format(title, message) if title else message text = f"{title}\n{message}" if title else message
params = self._get_msg_kwargs(kwargs) params = self._get_msg_kwargs(kwargs)
for chat_id in self._get_target_chat_ids(target): for chat_id in self._get_target_chat_ids(target):
_LOGGER.debug("Send message in chat ID %s with params: %s", chat_id, params) _LOGGER.debug("Send message in chat ID %s with params: %s", chat_id, params)
@ -590,7 +590,7 @@ class TelegramNotificationService:
if type_edit == SERVICE_EDIT_MESSAGE: if type_edit == SERVICE_EDIT_MESSAGE:
message = kwargs.get(ATTR_MESSAGE) message = kwargs.get(ATTR_MESSAGE)
title = kwargs.get(ATTR_TITLE) title = kwargs.get(ATTR_TITLE)
text = "{}\n{}".format(title, message) if title else message text = f"{title}\n{message}" if title else message
_LOGGER.debug( _LOGGER.debug(
"Editing message with ID %s.", message_id or inline_message_id "Editing message with ID %s.", message_id or inline_message_id
) )

View File

@ -45,7 +45,7 @@ async def async_setup_platform(hass, config):
else: else:
_LOGGER.debug("telegram webhook Status: %s", current_status) _LOGGER.debug("telegram webhook Status: %s", current_status)
handler_url = "{0}{1}".format(base_url, TELEGRAM_HANDLER_URL) handler_url = f"{base_url}{TELEGRAM_HANDLER_URL}"
if not handler_url.startswith("https"): if not handler_url.startswith("https"):
_LOGGER.error("Invalid telegram webhook %s must be https", handler_url) _LOGGER.error("Invalid telegram webhook %s must be https", handler_url)
return False return False

View File

@ -46,7 +46,7 @@ DATA_CONFIG_ENTRY_LOCK = "tellduslive_config_entry_lock"
CONFIG_ENTRY_IS_SETUP = "telldus_config_entry_is_setup" CONFIG_ENTRY_IS_SETUP = "telldus_config_entry_is_setup"
NEW_CLIENT_TASK = "telldus_new_client_task" NEW_CLIENT_TASK = "telldus_new_client_task"
INTERVAL_TRACKER = "{}_INTERVAL".format(DOMAIN) INTERVAL_TRACKER = f"{DOMAIN}_INTERVAL"
async def async_setup_entry(hass, entry): async def async_setup_entry(hass, entry):

View File

@ -107,7 +107,7 @@ class TellstickSensor(Entity):
self._unit_of_measurement = sensor_info.unit or None self._unit_of_measurement = sensor_info.unit or None
self._value = None self._value = None
self._name = "{} {}".format(name, sensor_info.name) self._name = f"{name} {sensor_info.name}"
@property @property
def name(self): def name(self):

View File

@ -43,13 +43,13 @@ class TeslaSensor(TeslaDevice, Entity):
super().__init__(tesla_device, controller) super().__init__(tesla_device, controller)
if self.type: if self.type:
self._name = "{} ({})".format(self.tesla_device.name, self.type) self._name = f"{self.tesla_device.name} ({self.type})"
@property @property
def unique_id(self) -> str: def unique_id(self) -> str:
"""Return a unique ID.""" """Return a unique ID."""
if self.type: if self.type:
return "{}_{}".format(self.tesla_id, self.type) return f"{self.tesla_id}_{self.type}"
return self.tesla_id return self.tesla_id
@property @property

View File

@ -86,7 +86,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
add_entities(dev, True) add_entities(dev, True)
except HTTPError as error: except HTTPError as error:
msg = "{}".format(error.strerror) msg = f"{error.strerror}"
if "EMAIL_NOT_FOUND" in msg or "INVALID_PASSWORD" in msg: if "EMAIL_NOT_FOUND" in msg or "INVALID_PASSWORD" in msg:
_LOGGER.error("Invalid email and password combination") _LOGGER.error("Invalid email and password combination")
else: else:
@ -105,7 +105,7 @@ class ThermoworksSmokeSensor(Entity):
self._state = None self._state = None
self._attributes = {} self._attributes = {}
self._unit_of_measurement = TEMP_FAHRENHEIT self._unit_of_measurement = TEMP_FAHRENHEIT
self._unique_id = "{serial}-{type}".format(serial=serial, type=sensor_type) self._unique_id = f"{serial}-{sensor_type}"
self.serial = serial self.serial = serial
self.mgr = mgr self.mgr = mgr
self.update_unit() self.update_unit()

View File

@ -65,7 +65,7 @@ class TtnDataSensor(Entity):
self._device_id = device_id self._device_id = device_id
self._unit_of_measurement = unit_of_measurement self._unit_of_measurement = unit_of_measurement
self._value = value self._value = value
self._name = "{} {}".format(self._device_id, self._value) self._name = f"{self._device_id} {self._value}"
@property @property
def name(self): def name(self):
@ -116,10 +116,7 @@ class TtnDataStorage:
self._url = TTN_DATA_STORAGE_URL.format( self._url = TTN_DATA_STORAGE_URL.format(
app_id=app_id, endpoint="api/v2/query", device_id=device_id app_id=app_id, endpoint="api/v2/query", device_id=device_id
) )
self._headers = { self._headers = {ACCEPT: CONTENT_TYPE_JSON, AUTHORIZATION: f"key {access_key}"}
ACCEPT: CONTENT_TYPE_JSON,
AUTHORIZATION: "key {}".format(access_key),
}
async def async_update(self): async def async_update(self):
"""Get the current state from The Things Network Data Storage.""" """Get the current state from The Things Network Data Storage."""

View File

@ -149,7 +149,7 @@ class TibberSensorRT(Entity):
self._device_state_attributes = {} self._device_state_attributes = {}
self._unit_of_measurement = "W" self._unit_of_measurement = "W"
nickname = tibber_home.info["viewer"]["home"]["appNickname"] nickname = tibber_home.info["viewer"]["home"]["appNickname"]
self._name = "Real time consumption {}".format(nickname) self._name = f"Real time consumption {nickname}"
async def async_added_to_hass(self): async def async_added_to_hass(self):
"""Start unavailability tracking.""" """Start unavailability tracking."""
@ -215,4 +215,4 @@ class TibberSensorRT(Entity):
"""Return a unique ID.""" """Return a unique ID."""
home = self._tibber_home.info["viewer"]["home"] home = self._tibber_home.info["viewer"]["home"]
_id = home["meteringPointData"]["consumptionEan"] _id = home["meteringPointData"]["consumptionEan"]
return "{}_rt_consumption".format(_id) return f"{_id}_rt_consumption"

View File

@ -118,15 +118,15 @@ class TimeDateSensor(Entity):
elif self.type == "date": elif self.type == "date":
self._state = date self._state = date
elif self.type == "date_time": elif self.type == "date_time":
self._state = "{}, {}".format(date, time) self._state = f"{date}, {time}"
elif self.type == "time_date": elif self.type == "time_date":
self._state = "{}, {}".format(time, date) self._state = f"{time}, {date}"
elif self.type == "time_utc": elif self.type == "time_utc":
self._state = time_utc self._state = time_utc
elif self.type == "beat": elif self.type == "beat":
self._state = "@{0:03d}".format(beat) self._state = f"@{beat:03d}"
elif self.type == "date_time_iso": elif self.type == "date_time_iso":
self._state = dt_util.parse_datetime("{} {}".format(date, time)).isoformat() self._state = dt_util.parse_datetime(f"{date} {time}").isoformat()
@callback @callback
def point_in_time_listener(self, time_date): def point_in_time_listener(self, time_date):

View File

@ -168,8 +168,8 @@ class Tplink1DeviceScanner(DeviceScanner):
""" """
_LOGGER.info("Loading wireless clients...") _LOGGER.info("Loading wireless clients...")
url = "http://{}/userRpm/WlanStationRpm.htm".format(self.host) url = f"http://{self.host}/userRpm/WlanStationRpm.htm"
referer = "http://{}".format(self.host) referer = f"http://{self.host}"
page = requests.get( page = requests.get(
url, url,
auth=(self.username, self.password), auth=(self.username, self.password),
@ -205,16 +205,16 @@ class Tplink2DeviceScanner(Tplink1DeviceScanner):
""" """
_LOGGER.info("Loading wireless clients...") _LOGGER.info("Loading wireless clients...")
url = "http://{}/data/map_access_wireless_client_grid.json".format(self.host) url = f"http://{self.host}/data/map_access_wireless_client_grid.json"
referer = "http://{}".format(self.host) referer = f"http://{self.host}"
# Router uses Authorization cookie instead of header # Router uses Authorization cookie instead of header
# Let's create the cookie # Let's create the cookie
username_password = "{}:{}".format(self.username, self.password) username_password = f"{self.username}:{self.password}"
b64_encoded_username_password = base64.b64encode( b64_encoded_username_password = base64.b64encode(
username_password.encode("ascii") username_password.encode("ascii")
).decode("ascii") ).decode("ascii")
cookie = "Authorization=Basic {}".format(b64_encoded_username_password) cookie = f"Authorization=Basic {b64_encoded_username_password}"
response = requests.post( response = requests.post(
url, headers={REFERER: referer, COOKIE: cookie}, timeout=4 url, headers={REFERER: referer, COOKIE: cookie}, timeout=4
@ -264,8 +264,8 @@ class Tplink3DeviceScanner(Tplink1DeviceScanner):
"""Retrieve auth tokens from the router.""" """Retrieve auth tokens from the router."""
_LOGGER.info("Retrieving auth tokens...") _LOGGER.info("Retrieving auth tokens...")
url = "http://{}/cgi-bin/luci/;stok=/login?form=login".format(self.host) url = f"http://{self.host}/cgi-bin/luci/;stok=/login?form=login"
referer = "http://{}/webpages/login.html".format(self.host) referer = f"http://{self.host}/webpages/login.html"
# If possible implement RSA encryption of password here. # If possible implement RSA encryption of password here.
response = requests.post( response = requests.post(
@ -303,7 +303,7 @@ class Tplink3DeviceScanner(Tplink1DeviceScanner):
url = ( url = (
"http://{}/cgi-bin/luci/;stok={}/admin/wireless?" "form=statistics" "http://{}/cgi-bin/luci/;stok={}/admin/wireless?" "form=statistics"
).format(self.host, self.stok) ).format(self.host, self.stok)
referer = "http://{}/webpages/index.html".format(self.host) referer = f"http://{self.host}/webpages/index.html"
response = requests.post( response = requests.post(
url, url,
@ -346,7 +346,7 @@ class Tplink3DeviceScanner(Tplink1DeviceScanner):
url = ("http://{}/cgi-bin/luci/;stok={}/admin/system?" "form=logout").format( url = ("http://{}/cgi-bin/luci/;stok={}/admin/system?" "form=logout").format(
self.host, self.stok self.host, self.stok
) )
referer = "http://{}/webpages/index.html".format(self.host) referer = f"http://{self.host}/webpages/index.html"
requests.post( requests.post(
url, url,
@ -379,19 +379,19 @@ class Tplink4DeviceScanner(Tplink1DeviceScanner):
def _get_auth_tokens(self): def _get_auth_tokens(self):
"""Retrieve auth tokens from the router.""" """Retrieve auth tokens from the router."""
_LOGGER.info("Retrieving auth tokens...") _LOGGER.info("Retrieving auth tokens...")
url = "http://{}/userRpm/LoginRpm.htm?Save=Save".format(self.host) url = f"http://{self.host}/userRpm/LoginRpm.htm?Save=Save"
# Generate md5 hash of password. The C7 appears to use the first 15 # Generate md5 hash of password. The C7 appears to use the first 15
# characters of the password only, so we truncate to remove additional # characters of the password only, so we truncate to remove additional
# characters from being hashed. # characters from being hashed.
password = hashlib.md5(self.password.encode("utf")[:15]).hexdigest() password = hashlib.md5(self.password.encode("utf")[:15]).hexdigest()
credentials = "{}:{}".format(self.username, password).encode("utf") credentials = f"{self.username}:{password}".encode("utf")
# Encode the credentials to be sent as a cookie. # Encode the credentials to be sent as a cookie.
self.credentials = base64.b64encode(credentials).decode("utf") self.credentials = base64.b64encode(credentials).decode("utf")
# Create the authorization cookie. # Create the authorization cookie.
cookie = "Authorization=Basic {}".format(self.credentials) cookie = f"Authorization=Basic {self.credentials}"
response = requests.get(url, headers={COOKIE: cookie}) response = requests.get(url, headers={COOKIE: cookie})
@ -423,9 +423,9 @@ class Tplink4DeviceScanner(Tplink1DeviceScanner):
# Check both the 2.4GHz and 5GHz client list URLs # Check both the 2.4GHz and 5GHz client list URLs
for clients_url in ("WlanStationRpm.htm", "WlanStationRpm_5g.htm"): for clients_url in ("WlanStationRpm.htm", "WlanStationRpm_5g.htm"):
url = "http://{}/{}/userRpm/{}".format(self.host, self.token, clients_url) url = f"http://{self.host}/{self.token}/userRpm/{clients_url}"
referer = "http://{}".format(self.host) referer = f"http://{self.host}"
cookie = "Authorization=Basic {}".format(self.credentials) cookie = f"Authorization=Basic {self.credentials}"
page = requests.get(url, headers={COOKIE: cookie, REFERER: referer}) page = requests.get(url, headers={COOKIE: cookie, REFERER: referer})
mac_results.extend(self.parse_macs.findall(page.text)) mac_results.extend(self.parse_macs.findall(page.text))
@ -456,7 +456,7 @@ class Tplink5DeviceScanner(Tplink1DeviceScanner):
""" """
_LOGGER.info("Loading wireless clients...") _LOGGER.info("Loading wireless clients...")
base_url = "http://{}".format(self.host) base_url = f"http://{self.host}"
header = { header = {
USER_AGENT: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12;" USER_AGENT: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12;"
@ -466,7 +466,7 @@ class Tplink5DeviceScanner(Tplink1DeviceScanner):
ACCEPT_ENCODING: "gzip, deflate", ACCEPT_ENCODING: "gzip, deflate",
CONTENT_TYPE: "application/x-www-form-urlencoded; charset=UTF-8", CONTENT_TYPE: "application/x-www-form-urlencoded; charset=UTF-8",
HTTP_HEADER_X_REQUESTED_WITH: "XMLHttpRequest", HTTP_HEADER_X_REQUESTED_WITH: "XMLHttpRequest",
REFERER: "http://{}/".format(self.host), REFERER: f"http://{self.host}/",
CONNECTION: KEEP_ALIVE, CONNECTION: KEEP_ALIVE,
PRAGMA: HTTP_HEADER_NO_CACHE, PRAGMA: HTTP_HEADER_NO_CACHE,
CACHE_CONTROL: HTTP_HEADER_NO_CACHE, CACHE_CONTROL: HTTP_HEADER_NO_CACHE,
@ -484,7 +484,7 @@ class Tplink5DeviceScanner(Tplink1DeviceScanner):
# A timestamp is required to be sent as get parameter # A timestamp is required to be sent as get parameter
timestamp = int(datetime.now().timestamp() * 1e3) timestamp = int(datetime.now().timestamp() * 1e3)
client_list_url = "{}/data/monitor.client.client.json".format(base_url) client_list_url = f"{base_url}/data/monitor.client.client.json"
get_params = {"operation": "load", "_": timestamp} get_params = {"operation": "load", "_": timestamp}

View File

@ -24,7 +24,7 @@ from .const import (
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
TRACKER_UPDATE = "{}_tracker_update".format(DOMAIN) TRACKER_UPDATE = f"{DOMAIN}_tracker_update"
DEFAULT_ACCURACY = 200 DEFAULT_ACCURACY = 200
@ -83,7 +83,7 @@ async def handle_webhook(hass, webhook_id, request):
attrs, attrs,
) )
return web.Response(text="Setting location for {}".format(device), status=HTTP_OK) return web.Response(text=f"Setting location for {device}", status=HTTP_OK)
async def async_setup_entry(hass, entry): async def async_setup_entry(hass, entry):

View File

@ -57,7 +57,7 @@ class TradfriGroup(Light):
def __init__(self, group, api, gateway_id): def __init__(self, group, api, gateway_id):
"""Initialize a Group.""" """Initialize a Group."""
self._api = api self._api = api
self._unique_id = "group-{}-{}".format(gateway_id, group.id) self._unique_id = f"group-{gateway_id}-{group.id}"
self._group = group self._group = group
self._name = group.name self._name = group.name
@ -152,7 +152,7 @@ class TradfriLight(Light):
def __init__(self, light, api, gateway_id): def __init__(self, light, api, gateway_id):
"""Initialize a Light.""" """Initialize a Light."""
self._api = api self._api = api
self._unique_id = "light-{}-{}".format(gateway_id, light.id) self._unique_id = f"light-{gateway_id}-{light.id}"
self._light = None self._light = None
self._light_control = None self._light_control = None
self._light_data = None self._light_data = None

View File

@ -34,7 +34,7 @@ class TradfriSwitch(SwitchDevice):
def __init__(self, switch, api, gateway_id): def __init__(self, switch, api, gateway_id):
"""Initialize a switch.""" """Initialize a switch."""
self._api = api self._api = api
self._unique_id = "{}-{}".format(gateway_id, switch.id) self._unique_id = f"{gateway_id}-{switch.id}"
self._switch = None self._switch = None
self._socket_control = None self._socket_control = None
self._switch_data = None self._switch_data = None

View File

@ -147,7 +147,7 @@ class TrafikverketWeatherStation(Entity):
@property @property
def name(self): def name(self):
"""Return the name of the sensor.""" """Return the name of the sensor."""
return "{} {}".format(self._client, self._name) return f"{self._client} {self._name}"
@property @property
def icon(self): def icon(self):

View File

@ -63,7 +63,7 @@ class TransmissionSensor(Entity):
@property @property
def name(self): def name(self):
"""Return the name of the sensor.""" """Return the name of the sensor."""
return "{} {}".format(self.client_name, self._name) return f"{self.client_name} {self._name}"
@property @property
def state(self): def state(self):

View File

@ -84,7 +84,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
for repo in repositories: for repo in repositories:
if "/" not in repo: if "/" not in repo:
repo = "{0}/{1}".format(user.login, repo) repo = f"{user.login}/{repo}"
for sensor_type in config.get(CONF_MONITORED_CONDITIONS): for sensor_type in config.get(CONF_MONITORED_CONDITIONS):
sensors.append(TravisCISensor(travis, repo, user, branch, sensor_type)) sensors.append(TravisCISensor(travis, repo, user, branch, sensor_type))

View File

@ -40,28 +40,28 @@ async def async_setup_entry(
TwenteMilieuSensor( TwenteMilieuSensor(
twentemilieu, twentemilieu,
unique_id=entry.data[CONF_ID], unique_id=entry.data[CONF_ID],
name="{} Waste Pickup".format(WASTE_TYPE_NON_RECYCLABLE), name=f"{WASTE_TYPE_NON_RECYCLABLE} Waste Pickup",
waste_type=WASTE_TYPE_NON_RECYCLABLE, waste_type=WASTE_TYPE_NON_RECYCLABLE,
icon="mdi:delete-empty", icon="mdi:delete-empty",
), ),
TwenteMilieuSensor( TwenteMilieuSensor(
twentemilieu, twentemilieu,
unique_id=entry.data[CONF_ID], unique_id=entry.data[CONF_ID],
name="{} Waste Pickup".format(WASTE_TYPE_ORGANIC), name=f"{WASTE_TYPE_ORGANIC} Waste Pickup",
waste_type=WASTE_TYPE_ORGANIC, waste_type=WASTE_TYPE_ORGANIC,
icon="mdi:delete-empty", icon="mdi:delete-empty",
), ),
TwenteMilieuSensor( TwenteMilieuSensor(
twentemilieu, twentemilieu,
unique_id=entry.data[CONF_ID], unique_id=entry.data[CONF_ID],
name="{} Waste Pickup".format(WASTE_TYPE_PAPER), name=f"{WASTE_TYPE_PAPER} Waste Pickup",
waste_type=WASTE_TYPE_PAPER, waste_type=WASTE_TYPE_PAPER,
icon="mdi:delete-empty", icon="mdi:delete-empty",
), ),
TwenteMilieuSensor( TwenteMilieuSensor(
twentemilieu, twentemilieu,
unique_id=entry.data[CONF_ID], unique_id=entry.data[CONF_ID],
name="{} Waste Pickup".format(WASTE_TYPE_PLASTIC), name=f"{WASTE_TYPE_PLASTIC} Waste Pickup",
waste_type=WASTE_TYPE_PLASTIC, waste_type=WASTE_TYPE_PLASTIC,
icon="mdi:delete-empty", icon="mdi:delete-empty",
), ),
@ -110,7 +110,7 @@ class TwenteMilieuSensor(Entity):
@property @property
def unique_id(self) -> str: def unique_id(self) -> str:
"""Return the unique ID for this sensor.""" """Return the unique ID for this sensor."""
return "{}_{}_{}".format(DOMAIN, self._unique_id, self._waste_type) return f"{DOMAIN}_{self._unique_id}_{self._waste_type}"
@property @property
def should_poll(self) -> bool: def should_poll(self) -> bool:

View File

@ -11,7 +11,7 @@ CONF_AUTH_TOKEN = "auth_token"
DATA_TWILIO = DOMAIN DATA_TWILIO = DOMAIN
RECEIVED_DATA = "{}_data_received".format(DOMAIN) RECEIVED_DATA = f"{DOMAIN}_data_received"
CONFIG_SCHEMA = vol.Schema( CONFIG_SCHEMA = vol.Schema(
{ {

View File

@ -80,7 +80,7 @@ class UbusDeviceScanner(DeviceScanner):
self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);") self.parse_api_pattern = re.compile(r"(?P<param>\w*) = (?P<value>.*);")
self.last_results = {} self.last_results = {}
self.url = "http://{}/ubus".format(host) self.url = f"http://{host}/ubus"
self.session_id = _get_session_id(self.url, self.username, self.password) self.session_id = _get_session_id(self.url, self.username, self.password)
self.hostapd = [] self.hostapd = []

View File

@ -157,10 +157,10 @@ class UkTransportLiveBusTimeSensor(UkTransportSensor):
self._stop_atcocode = stop_atcocode self._stop_atcocode = stop_atcocode
self._bus_direction = bus_direction self._bus_direction = bus_direction
self._next_buses = [] self._next_buses = []
self._destination_re = re.compile("{}".format(bus_direction), re.IGNORECASE) self._destination_re = re.compile(f"{bus_direction}", re.IGNORECASE)
sensor_name = "Next bus to {}".format(bus_direction) sensor_name = f"Next bus to {bus_direction}"
stop_url = "bus/stop/{}/live.json".format(stop_atcocode) stop_url = f"bus/stop/{stop_atcocode}/live.json"
UkTransportSensor.__init__(self, sensor_name, api_app_id, api_app_key, stop_url) UkTransportSensor.__init__(self, sensor_name, api_app_id, api_app_key, stop_url)
self.update = Throttle(interval)(self._update) self.update = Throttle(interval)(self._update)
@ -220,8 +220,8 @@ class UkTransportLiveTrainTimeSensor(UkTransportSensor):
self._calling_at = calling_at self._calling_at = calling_at
self._next_trains = [] self._next_trains = []
sensor_name = "Next train to {}".format(calling_at) sensor_name = f"Next train to {calling_at}"
query_url = "train/station/{}/live.json".format(station_code) query_url = f"train/station/{station_code}/live.json"
UkTransportSensor.__init__( UkTransportSensor.__init__(
self, sensor_name, api_app_id, api_app_key, query_url self, sensor_name, api_app_id, api_app_key, query_url

View File

@ -238,7 +238,7 @@ class UniFiClientTracker(ScannerEntity):
@property @property
def unique_id(self) -> str: def unique_id(self) -> str:
"""Return a unique identifier for this client.""" """Return a unique identifier for this client."""
return "{}-{}".format(self.client.mac, self.controller.site) return f"{self.client.mac}-{self.controller.site}"
@property @property
def available(self) -> bool: def available(self) -> bool:

View File

@ -69,7 +69,7 @@ def update_items(controller, async_add_entities, switches, switches_off):
# block client # block client
for client_id in controller.option_block_clients: for client_id in controller.option_block_clients:
block_client_id = "block-{}".format(client_id) block_client_id = f"block-{client_id}"
if block_client_id in switches: if block_client_id in switches:
LOGGER.debug( LOGGER.debug(
@ -91,7 +91,7 @@ def update_items(controller, async_add_entities, switches, switches_off):
# control poe # control poe
for client_id in controller.api.clients: for client_id in controller.api.clients:
poe_client_id = "poe-{}".format(client_id) poe_client_id = f"poe-{client_id}"
if poe_client_id in switches: if poe_client_id in switches:
LOGGER.debug( LOGGER.debug(
@ -194,7 +194,7 @@ class UniFiPOEClientSwitch(UniFiClient, SwitchDevice, RestoreEntity):
@property @property
def unique_id(self): def unique_id(self):
"""Return a unique identifier for this switch.""" """Return a unique identifier for this switch."""
return "poe-{}".format(self.client.mac) return f"poe-{self.client.mac}"
@property @property
def is_on(self): def is_on(self):
@ -255,7 +255,7 @@ class UniFiBlockClientSwitch(UniFiClient, SwitchDevice):
@property @property
def unique_id(self): def unique_id(self):
"""Return a unique identifier for this switch.""" """Return a unique identifier for this switch."""
return "block-{}".format(self.client.mac) return f"block-{self.client.mac}"
@property @property
def is_on(self): def is_on(self):

View File

@ -48,7 +48,7 @@ class UPCDeviceScanner(DeviceScanner):
self.headers = { self.headers = {
HTTP_HEADER_X_REQUESTED_WITH: "XMLHttpRequest", HTTP_HEADER_X_REQUESTED_WITH: "XMLHttpRequest",
REFERER: "http://{}/index.html".format(self.host), REFERER: f"http://{self.host}/index.html",
USER_AGENT: ( USER_AGENT: (
"Mozilla/5.0 (Windows NT 10.0; WOW64) " "Mozilla/5.0 (Windows NT 10.0; WOW64) "
"AppleWebKit/537.36 (KHTML, like Gecko) " "AppleWebKit/537.36 (KHTML, like Gecko) "
@ -88,8 +88,7 @@ class UPCDeviceScanner(DeviceScanner):
# get first token # get first token
with async_timeout.timeout(10): with async_timeout.timeout(10):
response = await self.websession.get( response = await self.websession.get(
"http://{}/common_page/login.html".format(self.host), f"http://{self.host}/common_page/login.html", headers=self.headers
headers=self.headers,
) )
await response.text() await response.text()
@ -109,8 +108,8 @@ class UPCDeviceScanner(DeviceScanner):
# The 'token' parameter has to be first, and 'fun' second # The 'token' parameter has to be first, and 'fun' second
# or the UPC firmware will return an error # or the UPC firmware will return an error
response = await self.websession.post( response = await self.websession.post(
"http://{}/xml/getter.xml".format(self.host), f"http://{self.host}/xml/getter.xml",
data="token={}&fun={}".format(self.token, function), data=f"token={self.token}&fun={function}",
headers=self.headers, headers=self.headers,
allow_redirects=False, allow_redirects=False,
) )

View File

@ -118,7 +118,7 @@ class RawUPnPIGDSensor(UpnpSensor):
@property @property
def unique_id(self) -> str: def unique_id(self) -> str:
"""Return an unique ID.""" """Return an unique ID."""
return "{}_{}".format(self._device.udn, self._type_name) return f"{self._device.udn}_{self._type_name}"
@property @property
def state(self) -> str: def state(self) -> str:
@ -172,12 +172,12 @@ class PerSecondUPnPIGDSensor(UpnpSensor):
@property @property
def unique_id(self) -> str: def unique_id(self) -> str:
"""Return an unique ID.""" """Return an unique ID."""
return "{}_{}/sec_{}".format(self._device.udn, self.unit, self._direction) return f"{self._device.udn}_{self.unit}/sec_{self._direction}"
@property @property
def name(self) -> str: def name(self) -> str:
"""Return the name of the sensor.""" """Return the name of the sensor."""
return "{} {}/sec {}".format(self._device.name, self.unit, self._direction) return f"{self._device.name} {self.unit}/sec {self._direction}"
@property @property
def icon(self) -> str: def icon(self) -> str:
@ -187,7 +187,7 @@ class PerSecondUPnPIGDSensor(UpnpSensor):
@property @property
def unit_of_measurement(self) -> str: def unit_of_measurement(self) -> str:
"""Return the unit of measurement of this entity, if any.""" """Return the unit of measurement of this entity, if any."""
return "{}/sec".format(self.unit) return f"{self.unit}/sec"
def _is_overflowed(self, new_value) -> bool: def _is_overflowed(self, new_value) -> bool:
"""Check if value has overflowed.""" """Check if value has overflowed."""

View File

@ -65,7 +65,7 @@ class USPSCamera(Camera):
@property @property
def name(self): def name(self):
"""Return the name of this camera.""" """Return the name of this camera."""
return "{} mail".format(self._name) return f"{self._name} mail"
@property @property
def model(self): def model(self):

View File

@ -36,7 +36,7 @@ class USPSPackageSensor(Entity):
@property @property
def name(self): def name(self):
"""Return the name of the sensor.""" """Return the name of the sensor."""
return "{} packages".format(self._name) return f"{self._name} packages"
@property @property
def state(self): def state(self):
@ -85,7 +85,7 @@ class USPSMailSensor(Entity):
@property @property
def name(self): def name(self):
"""Return the name of the sensor.""" """Return the name of the sensor."""
return "{} mail".format(self._name) return f"{self._name} mail"
@property @property
def state(self): def state(self):

View File

@ -152,7 +152,7 @@ class ValloxStateProxy:
raise OSError("Device state out of sync.") raise OSError("Device state out of sync.")
if metric_key not in vlxDevConstants.__dict__: if metric_key not in vlxDevConstants.__dict__:
raise KeyError("Unknown metric key: {}".format(metric_key)) raise KeyError(f"Unknown metric key: {metric_key}")
return self._metric_cache[metric_key] return self._metric_cache[metric_key]

View File

@ -28,14 +28,14 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
sensors = [ sensors = [
ValloxProfileSensor( ValloxProfileSensor(
name="{} Current Profile".format(name), name=f"{name} Current Profile",
state_proxy=state_proxy, state_proxy=state_proxy,
device_class=None, device_class=None,
unit_of_measurement=None, unit_of_measurement=None,
icon="mdi:gauge", icon="mdi:gauge",
), ),
ValloxFanSpeedSensor( ValloxFanSpeedSensor(
name="{} Fan Speed".format(name), name=f"{name} Fan Speed",
state_proxy=state_proxy, state_proxy=state_proxy,
metric_key="A_CYC_FAN_SPEED", metric_key="A_CYC_FAN_SPEED",
device_class=None, device_class=None,
@ -43,7 +43,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
icon="mdi:fan", icon="mdi:fan",
), ),
ValloxSensor( ValloxSensor(
name="{} Extract Air".format(name), name=f"{name} Extract Air",
state_proxy=state_proxy, state_proxy=state_proxy,
metric_key="A_CYC_TEMP_EXTRACT_AIR", metric_key="A_CYC_TEMP_EXTRACT_AIR",
device_class=DEVICE_CLASS_TEMPERATURE, device_class=DEVICE_CLASS_TEMPERATURE,
@ -51,7 +51,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
icon=None, icon=None,
), ),
ValloxSensor( ValloxSensor(
name="{} Exhaust Air".format(name), name=f"{name} Exhaust Air",
state_proxy=state_proxy, state_proxy=state_proxy,
metric_key="A_CYC_TEMP_EXHAUST_AIR", metric_key="A_CYC_TEMP_EXHAUST_AIR",
device_class=DEVICE_CLASS_TEMPERATURE, device_class=DEVICE_CLASS_TEMPERATURE,
@ -59,7 +59,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
icon=None, icon=None,
), ),
ValloxSensor( ValloxSensor(
name="{} Outdoor Air".format(name), name=f"{name} Outdoor Air",
state_proxy=state_proxy, state_proxy=state_proxy,
metric_key="A_CYC_TEMP_OUTDOOR_AIR", metric_key="A_CYC_TEMP_OUTDOOR_AIR",
device_class=DEVICE_CLASS_TEMPERATURE, device_class=DEVICE_CLASS_TEMPERATURE,
@ -67,7 +67,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
icon=None, icon=None,
), ),
ValloxSensor( ValloxSensor(
name="{} Supply Air".format(name), name=f"{name} Supply Air",
state_proxy=state_proxy, state_proxy=state_proxy,
metric_key="A_CYC_TEMP_SUPPLY_AIR", metric_key="A_CYC_TEMP_SUPPLY_AIR",
device_class=DEVICE_CLASS_TEMPERATURE, device_class=DEVICE_CLASS_TEMPERATURE,
@ -75,7 +75,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
icon=None, icon=None,
), ),
ValloxSensor( ValloxSensor(
name="{} Humidity".format(name), name=f"{name} Humidity",
state_proxy=state_proxy, state_proxy=state_proxy,
metric_key="A_CYC_RH_VALUE", metric_key="A_CYC_RH_VALUE",
device_class=DEVICE_CLASS_HUMIDITY, device_class=DEVICE_CLASS_HUMIDITY,
@ -83,7 +83,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
icon=None, icon=None,
), ),
ValloxFilterRemainingSensor( ValloxFilterRemainingSensor(
name="{} Remaining Time For Filter".format(name), name=f"{name} Remaining Time For Filter",
state_proxy=state_proxy, state_proxy=state_proxy,
metric_key="A_CYC_REMAINING_TIME_FOR_FILTER", metric_key="A_CYC_REMAINING_TIME_FOR_FILTER",
device_class=DEVICE_CLASS_TIMESTAMP, device_class=DEVICE_CLASS_TIMESTAMP,

View File

@ -119,7 +119,7 @@ class VelbusEntity(Entity):
serial = self._module.get_module_address() serial = self._module.get_module_address()
else: else:
serial = self._module.serial serial = self._module.serial
return "{}-{}".format(serial, self._channel) return f"{serial}-{self._channel}"
@property @property
def name(self): def name(self):

View File

@ -125,7 +125,7 @@ class Volumio(MediaPlayerDevice):
async def send_volumio_msg(self, method, params=None): async def send_volumio_msg(self, method, params=None):
"""Send message.""" """Send message."""
url = "http://{}:{}/api/v1/{}/".format(self.host, self.port, method) url = f"http://{self.host}:{self.port}/api/v1/{method}/"
_LOGGER.debug("URL: %s params: %s", url, params) _LOGGER.debug("URL: %s params: %s", url, params)
@ -202,7 +202,7 @@ class Volumio(MediaPlayerDevice):
if str(url[0:2]).lower() == "ht": if str(url[0:2]).lower() == "ht":
mediaurl = url mediaurl = url
else: else:
mediaurl = "http://{}:{}{}".format(self.host, self.port, url) mediaurl = f"http://{self.host}:{self.port}{url}"
return mediaurl return mediaurl
@property @property

View File

@ -36,7 +36,7 @@ CONF_SERVICE_URL = "service_url"
CONF_SCANDINAVIAN_MILES = "scandinavian_miles" CONF_SCANDINAVIAN_MILES = "scandinavian_miles"
CONF_MUTABLE = "mutable" CONF_MUTABLE = "mutable"
SIGNAL_STATE_UPDATED = "{}.updated".format(DOMAIN) SIGNAL_STATE_UPDATED = f"{DOMAIN}.updated"
COMPONENTS = { COMPONENTS = {
"sensor": "sensor", "sensor": "sensor",
@ -261,7 +261,7 @@ class VolvoEntity(Entity):
@property @property
def name(self): def name(self):
"""Return full name of the entity.""" """Return full name of the entity."""
return "{} {}".format(self._vehicle_name, self._entity_name) return f"{self._vehicle_name} {self._entity_name}"
@property @property
def should_poll(self): def should_poll(self):
@ -278,5 +278,5 @@ class VolvoEntity(Entity):
"""Return device specific state attributes.""" """Return device specific state attributes."""
return dict( return dict(
self.instrument.attributes, self.instrument.attributes,
model="{}/{}".format(self.vehicle.vehicle_type, self.vehicle.model_year), model=f"{self.vehicle.vehicle_type}/{self.vehicle.model_year}",
) )

View File

@ -113,7 +113,7 @@ class WaqiSensor(Entity):
def name(self): def name(self):
"""Return the name of the sensor.""" """Return the name of the sensor."""
if self.station_name: if self.station_name:
return "WAQI {}".format(self.station_name) return f"WAQI {self.station_name}"
return "WAQI {}".format(self.url if self.url else self.uid) return "WAQI {}".format(self.url if self.url else self.uid)
@property @property

View File

@ -126,7 +126,7 @@ def setup(hass, config):
if key != "unit_of_measurement": if key != "unit_of_measurement":
# If the key is already in fields # If the key is already in fields
if key in out_event["fields"]: if key in out_event["fields"]:
key = "{}_".format(key) key = f"{key}_"
# For each value we try to cast it as float # For each value we try to cast it as float
# But if we can not do it we store the value # But if we can not do it we store the value
# as string # as string

View File

@ -175,7 +175,7 @@ class WazeTravelTime(Entity):
return _get_location_from_attributes(state) return _get_location_from_attributes(state)
# Check if device is inside a zone. # Check if device is inside a zone.
zone_state = self.hass.states.get("zone.{}".format(state.state)) zone_state = self.hass.states.get(f"zone.{state.state}")
if location.has_location(zone_state): if location.has_location(zone_state):
_LOGGER.debug( _LOGGER.debug(
"%s is in %s, getting zone location", entity_id, zone_state.entity_id "%s is in %s, getting zone location", entity_id, zone_state.entity_id

View File

@ -108,7 +108,7 @@ async def async_setup_entry(hass, entry):
def setup_url_for_device(device): def setup_url_for_device(device):
"""Determine setup.xml url for given device.""" """Determine setup.xml url for given device."""
return "http://{}:{}/setup.xml".format(device.host, device.port) return f"http://{device.host}:{device.port}/setup.xml"
def setup_url_for_address(host, port): def setup_url_for_address(host, port):
"""Determine setup.xml url for given host and port pair.""" """Determine setup.xml url for given host and port pair."""
@ -118,7 +118,7 @@ async def async_setup_entry(hass, entry):
if not port: if not port:
return None return None
return "http://{}:{}/setup.xml".format(host, port) return f"http://{host}:{port}/setup.xml"
def discovery_dispatch(service, discovery_info): def discovery_dispatch(service, discovery_info):
"""Dispatcher for incoming WeMo discovery events.""" """Dispatcher for incoming WeMo discovery events."""
@ -150,7 +150,7 @@ async def async_setup_entry(hass, entry):
if not url: if not url:
_LOGGER.error( _LOGGER.error(
"Unable to get description url for WeMo at: %s", "Unable to get description url for WeMo at: %s",
"{}:{}".format(host, port) if port else host, f"{host}:{port}" if port else host,
) )
continue continue

View File

@ -52,7 +52,7 @@ ATTR_HUB_NAME = "hub_name"
WINK_AUTH_CALLBACK_PATH = "/auth/wink/callback" WINK_AUTH_CALLBACK_PATH = "/auth/wink/callback"
WINK_AUTH_START = "/auth/wink" WINK_AUTH_START = "/auth/wink"
WINK_CONFIG_FILE = ".wink.conf" WINK_CONFIG_FILE = ".wink.conf"
USER_AGENT = "Manufacturer/Home-Assistant{} python/3 Wink/3".format(__version__) USER_AGENT = f"Manufacturer/Home-Assistant{__version__} python/3 Wink/3"
DEFAULT_CONFIG = {"client_id": "CLIENT_ID_HERE", "client_secret": "CLIENT_SECRET_HERE"} DEFAULT_CONFIG = {"client_id": "CLIENT_ID_HERE", "client_secret": "CLIENT_SECRET_HERE"}
@ -228,7 +228,7 @@ def _request_app_setup(hass, config):
_configurator = hass.data[DOMAIN]["configuring"][DOMAIN] _configurator = hass.data[DOMAIN]["configuring"][DOMAIN]
configurator.notify_errors(_configurator, error_msg) configurator.notify_errors(_configurator, error_msg)
start_url = "{}{}".format(hass.config.api.base_url, WINK_AUTH_CALLBACK_PATH) start_url = f"{hass.config.api.base_url}{WINK_AUTH_CALLBACK_PATH}"
description = """Please create a Wink developer app at description = """Please create a Wink developer app at
https://developer.wink.com. https://developer.wink.com.
@ -268,9 +268,9 @@ def _request_oauth_completion(hass, config):
"""Call setup again.""" """Call setup again."""
setup(hass, config) setup(hass, config)
start_url = "{}{}".format(hass.config.api.base_url, WINK_AUTH_START) start_url = f"{hass.config.api.base_url}{WINK_AUTH_START}"
description = "Please authorize Wink by visiting {}".format(start_url) description = f"Please authorize Wink by visiting {start_url}"
hass.data[DOMAIN]["configuring"][DOMAIN] = configurator.request_config( hass.data[DOMAIN]["configuring"][DOMAIN] = configurator.request_config(
DOMAIN, wink_configuration_callback, description=description DOMAIN, wink_configuration_callback, description=description

View File

@ -140,7 +140,7 @@ class WinkHub(WinkBinarySensorDevice):
# The service call to set the Kidde code # The service call to set the Kidde code
# takes a string of 1s and 0s so it makes # takes a string of 1s and 0s so it makes
# sense to display it to the user that way # sense to display it to the user that way
_formatted_kidde_code = "{:b}".format(_kidde_code).zfill(8) _formatted_kidde_code = f"{_kidde_code:b}".zfill(8)
_attributes["kidde_radio_code"] = _formatted_kidde_code _attributes["kidde_radio_code"] = _formatted_kidde_code
return _attributes return _attributes

View File

@ -74,14 +74,14 @@ class WirelessTagPlatform:
def arm(self, switch): def arm(self, switch):
"""Arm entity sensor monitoring.""" """Arm entity sensor monitoring."""
func_name = "arm_{}".format(switch.sensor_type) func_name = f"arm_{switch.sensor_type}"
arm_func = getattr(self.api, func_name) arm_func = getattr(self.api, func_name)
if arm_func is not None: if arm_func is not None:
arm_func(switch.tag_id, switch.tag_manager_mac) arm_func(switch.tag_id, switch.tag_manager_mac)
def disarm(self, switch): def disarm(self, switch):
"""Disarm entity sensor monitoring.""" """Disarm entity sensor monitoring."""
func_name = "disarm_{}".format(switch.sensor_type) func_name = f"disarm_{switch.sensor_type}"
disarm_func = getattr(self.api, func_name) disarm_func = getattr(self.api, func_name)
if disarm_func is not None: if disarm_func is not None:
disarm_func(switch.tag_id, switch.tag_manager_mac) disarm_func(switch.tag_id, switch.tag_manager_mac)
@ -132,18 +132,18 @@ class WirelessTagPlatform:
port = self.hass.config.api.port port = self.hass.config.api.port
if port is not None: if port is not None:
self._local_base_url += ":{}".format(port) self._local_base_url += f":{port}"
return self._local_base_url return self._local_base_url
@property @property
def update_callback_url(self): def update_callback_url(self):
"""Return url for local push notifications(update event).""" """Return url for local push notifications(update event)."""
return "{}/api/events/wirelesstag_update_tags".format(self.local_base_url) return f"{self.local_base_url}/api/events/wirelesstag_update_tags"
@property @property
def binary_event_callback_url(self): def binary_event_callback_url(self):
"""Return url for local push notifications(binary event).""" """Return url for local push notifications(binary event)."""
return "{}/api/events/wirelesstag_binary_event".format(self.local_base_url) return f"{self.local_base_url}/api/events/wirelesstag_binary_event"
def handle_update_tags_event(self, event): def handle_update_tags_event(self, event):
"""Handle push event from wireless tag manager.""" """Handle push event from wireless tag manager."""
@ -254,7 +254,7 @@ class WirelessTagBaseSensor(Entity):
# pylint: disable=no-self-use # pylint: disable=no-self-use
def decorate_value(self, value): def decorate_value(self, value):
"""Decorate input value to be well presented for end user.""" """Decorate input value to be well presented for end user."""
return "{:.1f}".format(value) return f"{value:.1f}"
@property @property
def available(self): def available(self):
@ -280,8 +280,8 @@ class WirelessTagBaseSensor(Entity):
"""Return the state attributes.""" """Return the state attributes."""
return { return {
ATTR_BATTERY_LEVEL: int(self._tag.battery_remaining * 100), ATTR_BATTERY_LEVEL: int(self._tag.battery_remaining * 100),
ATTR_VOLTAGE: "{:.2f}V".format(self._tag.battery_volts), ATTR_VOLTAGE: f"{self._tag.battery_volts:.2f}V",
ATTR_TAG_SIGNAL_STRENGTH: "{}dBm".format(self._tag.signal_strength), ATTR_TAG_SIGNAL_STRENGTH: f"{self._tag.signal_strength}dBm",
ATTR_TAG_OUT_OF_RANGE: not self._tag.is_in_range, ATTR_TAG_OUT_OF_RANGE: not self._tag.is_in_range,
ATTR_TAG_POWER_CONSUMPTION: "{:.2f}%".format(self._tag.power_consumption), ATTR_TAG_POWER_CONSUMPTION: f"{self._tag.power_consumption:.2f}%",
} }

View File

@ -95,7 +95,7 @@ class WirelessTagBinarySensor(WirelessTagBaseSensor, BinarySensorDevice):
"""Initialize a binary sensor for a Wireless Sensor Tags.""" """Initialize a binary sensor for a Wireless Sensor Tags."""
super().__init__(api, tag) super().__init__(api, tag)
self._sensor_type = sensor_type self._sensor_type = sensor_type
self._name = "{0} {1}".format(self._tag.name, self.event.human_readable_name) self._name = f"{self._tag.name} {self.event.human_readable_name}"
async def async_added_to_hass(self): async def async_added_to_hass(self):
"""Register callbacks.""" """Register callbacks."""

View File

@ -79,5 +79,5 @@ class WirelessTagSwitch(WirelessTagBaseSensor, SwitchDevice):
@property @property
def principal_value(self): def principal_value(self):
"""Provide actual value of switch.""" """Provide actual value of switch."""
attr_name = "is_{}_sensor_armed".format(self.sensor_type) attr_name = f"is_{self.sensor_type}_sensor_armed"
return getattr(self._tag, attr_name, False) return getattr(self._tag, attr_name, False)

View File

@ -325,7 +325,7 @@ class WithingsHealthSensor(Entity):
@property @property
def name(self) -> str: def name(self) -> str:
"""Return the name of the sensor.""" """Return the name of the sensor."""
return "Withings {} {}".format(self._attribute.measurement, self._slug) return f"Withings {self._attribute.measurement} {self._slug}"
@property @property
def unique_id(self) -> str: def unique_id(self) -> str:

View File

@ -96,12 +96,12 @@ class WorldTidesInfoSensor(Entity):
tidetime = time.strftime( tidetime = time.strftime(
"%I:%M %p", time.localtime(self.data["extremes"][0]["dt"]) "%I:%M %p", time.localtime(self.data["extremes"][0]["dt"])
) )
return "High tide at {}".format(tidetime) return f"High tide at {tidetime}"
if "Low" in str(self.data["extremes"][0]["type"]): if "Low" in str(self.data["extremes"][0]["type"]):
tidetime = time.strftime( tidetime = time.strftime(
"%I:%M %p", time.localtime(self.data["extremes"][0]["dt"]) "%I:%M %p", time.localtime(self.data["extremes"][0]["dt"])
) )
return "Low tide at {}".format(tidetime) return f"Low tide at {tidetime}"
return None return None
return None return None

View File

@ -63,12 +63,12 @@ class WorxLandroidSensor(Entity):
self.pin = config.get(CONF_PIN) self.pin = config.get(CONF_PIN)
self.timeout = config.get(CONF_TIMEOUT) self.timeout = config.get(CONF_TIMEOUT)
self.allow_unreachable = config.get(CONF_ALLOW_UNREACHABLE) self.allow_unreachable = config.get(CONF_ALLOW_UNREACHABLE)
self.url = "http://{}/jsondata.cgi".format(self.host) self.url = f"http://{self.host}/jsondata.cgi"
@property @property
def name(self): def name(self):
"""Return the name of the sensor.""" """Return the name of the sensor."""
return "worxlandroid-{}".format(self.sensor) return f"worxlandroid-{self.sensor}"
@property @property
def state(self): def state(self):

View File

@ -968,7 +968,7 @@ async def async_setup_platform(
) )
if pws_id is None: if pws_id is None:
unique_id_base = "@{:06f},{:06f}".format(longitude, latitude) unique_id_base = f"@{longitude:06f},{latitude:06f}"
else: else:
# Manually specified weather station, use that for unique_id # Manually specified weather station, use that for unique_id
unique_id_base = pws_id unique_id_base = pws_id
@ -999,7 +999,7 @@ class WUndergroundSensor(Entity):
# This is only the suggested entity id, it might get changed by # This is only the suggested entity id, it might get changed by
# the entity registry later. # the entity registry later.
self.entity_id = sensor.ENTITY_ID_FORMAT.format("pws_" + condition) self.entity_id = sensor.ENTITY_ID_FORMAT.format("pws_" + condition)
self._unique_id = "{},{}".format(unique_id_base, condition) self._unique_id = f"{unique_id_base},{condition}"
self._device_class = self._cfg_expand("device_class") self._device_class = self._cfg_expand("device_class")
def _cfg_expand(self, what, default=None): def _cfg_expand(self, what, default=None):
@ -1106,7 +1106,7 @@ class WUndergroundData:
self._hass = hass self._hass = hass
self._api_key = api_key self._api_key = api_key
self._pws_id = pws_id self._pws_id = pws_id
self._lang = "lang:{}".format(lang) self._lang = f"lang:{lang}"
self._latitude = latitude self._latitude = latitude
self._longitude = longitude self._longitude = longitude
self._features = set() self._features = set()
@ -1122,9 +1122,9 @@ class WUndergroundData:
self._api_key, "/".join(sorted(self._features)), self._lang self._api_key, "/".join(sorted(self._features)), self._lang
) )
if self._pws_id: if self._pws_id:
url = url + "pws:{}".format(self._pws_id) url = url + f"pws:{self._pws_id}"
else: else:
url = url + "{},{}".format(self._latitude, self._longitude) url = url + f"{self._latitude},{self._longitude}"
return url + ".json" return url + ".json"

View File

@ -47,7 +47,7 @@ async def async_setup(hass, config):
latitude = conf.get(CONF_LATITUDE, hass.config.latitude) latitude = conf.get(CONF_LATITUDE, hass.config.latitude)
longitude = conf.get(CONF_LONGITUDE, hass.config.longitude) longitude = conf.get(CONF_LONGITUDE, hass.config.longitude)
identifier = "{0}, {1}".format(latitude, longitude) identifier = f"{latitude}, {longitude}"
if identifier in configured_instances(hass): if identifier in configured_instances(hass):
return True return True