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"])
step = temperatures["celsius"].get("step", PRECISION_TENTHS)
data_id = "zone {} {}".format(name, zone_id)
data_id = f"zone {name} {zone_id}"
device = TadoClimate(
tado,
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):
"""Create a zone sensor."""
data_id = "zone {} {}".format(name, zone_id)
data_id = f"zone {name} {zone_id}"
tado.add_sensor(
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):
"""Create a device sensor."""
data_id = "device {} {}".format(name, device_id)
data_id = f"device {name} {device_id}"
tado.add_sensor(
data_id,
@ -118,7 +118,7 @@ class TadoSensor(Entity):
self.zone_id = zone_id
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._state = None
@ -132,7 +132,7 @@ class TadoSensor(Entity):
@property
def name(self):
"""Return the name of the sensor."""
return "{} {}".format(self.zone_name, self.zone_variable)
return f"{self.zone_name} {self.zone_variable}"
@property
def state(self):

View File

@ -45,7 +45,7 @@ class TapsAffSensor(BinarySensorDevice):
@property
def name(self):
"""Return the name of the sensor."""
return "{}".format(self._name)
return f"{self._name}"
@property
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)
port = config.get(CONF_PORT)
name = config.get(CONF_NAME)
url = "http://{}:{}/api/LiveData.xml".format(host, port)
url = f"http://{host}:{port}/api/LiveData.xml"
gateway = Ted5000Gateway(url)

View File

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

View File

@ -554,7 +554,7 @@ class TelegramNotificationService:
def send_message(self, message="", target=None, **kwargs):
"""Send a message to one or multiple pre-allowed chat IDs."""
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)
for chat_id in self._get_target_chat_ids(target):
_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:
message = kwargs.get(ATTR_MESSAGE)
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(
"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:
_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"):
_LOGGER.error("Invalid telegram webhook %s must be https", handler_url)
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"
NEW_CLIENT_TASK = "telldus_new_client_task"
INTERVAL_TRACKER = "{}_INTERVAL".format(DOMAIN)
INTERVAL_TRACKER = f"{DOMAIN}_INTERVAL"
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._value = None
self._name = "{} {}".format(name, sensor_info.name)
self._name = f"{name} {sensor_info.name}"
@property
def name(self):

View File

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

View File

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

View File

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

View File

@ -149,7 +149,7 @@ class TibberSensorRT(Entity):
self._device_state_attributes = {}
self._unit_of_measurement = "W"
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):
"""Start unavailability tracking."""
@ -215,4 +215,4 @@ class TibberSensorRT(Entity):
"""Return a unique ID."""
home = self._tibber_home.info["viewer"]["home"]
_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":
self._state = date
elif self.type == "date_time":
self._state = "{}, {}".format(date, time)
self._state = f"{date}, {time}"
elif self.type == "time_date":
self._state = "{}, {}".format(time, date)
self._state = f"{time}, {date}"
elif self.type == "time_utc":
self._state = time_utc
elif self.type == "beat":
self._state = "@{0:03d}".format(beat)
self._state = f"@{beat:03d}"
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
def point_in_time_listener(self, time_date):

View File

@ -168,8 +168,8 @@ class Tplink1DeviceScanner(DeviceScanner):
"""
_LOGGER.info("Loading wireless clients...")
url = "http://{}/userRpm/WlanStationRpm.htm".format(self.host)
referer = "http://{}".format(self.host)
url = f"http://{self.host}/userRpm/WlanStationRpm.htm"
referer = f"http://{self.host}"
page = requests.get(
url,
auth=(self.username, self.password),
@ -205,16 +205,16 @@ class Tplink2DeviceScanner(Tplink1DeviceScanner):
"""
_LOGGER.info("Loading wireless clients...")
url = "http://{}/data/map_access_wireless_client_grid.json".format(self.host)
referer = "http://{}".format(self.host)
url = f"http://{self.host}/data/map_access_wireless_client_grid.json"
referer = f"http://{self.host}"
# Router uses Authorization cookie instead of header
# 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(
username_password.encode("ascii")
).decode("ascii")
cookie = "Authorization=Basic {}".format(b64_encoded_username_password)
cookie = f"Authorization=Basic {b64_encoded_username_password}"
response = requests.post(
url, headers={REFERER: referer, COOKIE: cookie}, timeout=4
@ -264,8 +264,8 @@ class Tplink3DeviceScanner(Tplink1DeviceScanner):
"""Retrieve auth tokens from the router."""
_LOGGER.info("Retrieving auth tokens...")
url = "http://{}/cgi-bin/luci/;stok=/login?form=login".format(self.host)
referer = "http://{}/webpages/login.html".format(self.host)
url = f"http://{self.host}/cgi-bin/luci/;stok=/login?form=login"
referer = f"http://{self.host}/webpages/login.html"
# If possible implement RSA encryption of password here.
response = requests.post(
@ -303,7 +303,7 @@ class Tplink3DeviceScanner(Tplink1DeviceScanner):
url = (
"http://{}/cgi-bin/luci/;stok={}/admin/wireless?" "form=statistics"
).format(self.host, self.stok)
referer = "http://{}/webpages/index.html".format(self.host)
referer = f"http://{self.host}/webpages/index.html"
response = requests.post(
url,
@ -346,7 +346,7 @@ class Tplink3DeviceScanner(Tplink1DeviceScanner):
url = ("http://{}/cgi-bin/luci/;stok={}/admin/system?" "form=logout").format(
self.host, self.stok
)
referer = "http://{}/webpages/index.html".format(self.host)
referer = f"http://{self.host}/webpages/index.html"
requests.post(
url,
@ -379,19 +379,19 @@ class Tplink4DeviceScanner(Tplink1DeviceScanner):
def _get_auth_tokens(self):
"""Retrieve auth tokens from the router."""
_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
# characters of the password only, so we truncate to remove additional
# characters from being hashed.
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.
self.credentials = base64.b64encode(credentials).decode("utf")
# Create the authorization cookie.
cookie = "Authorization=Basic {}".format(self.credentials)
cookie = f"Authorization=Basic {self.credentials}"
response = requests.get(url, headers={COOKIE: cookie})
@ -423,9 +423,9 @@ class Tplink4DeviceScanner(Tplink1DeviceScanner):
# Check both the 2.4GHz and 5GHz client list URLs
for clients_url in ("WlanStationRpm.htm", "WlanStationRpm_5g.htm"):
url = "http://{}/{}/userRpm/{}".format(self.host, self.token, clients_url)
referer = "http://{}".format(self.host)
cookie = "Authorization=Basic {}".format(self.credentials)
url = f"http://{self.host}/{self.token}/userRpm/{clients_url}"
referer = f"http://{self.host}"
cookie = f"Authorization=Basic {self.credentials}"
page = requests.get(url, headers={COOKIE: cookie, REFERER: referer})
mac_results.extend(self.parse_macs.findall(page.text))
@ -456,7 +456,7 @@ class Tplink5DeviceScanner(Tplink1DeviceScanner):
"""
_LOGGER.info("Loading wireless clients...")
base_url = "http://{}".format(self.host)
base_url = f"http://{self.host}"
header = {
USER_AGENT: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12;"
@ -466,7 +466,7 @@ class Tplink5DeviceScanner(Tplink1DeviceScanner):
ACCEPT_ENCODING: "gzip, deflate",
CONTENT_TYPE: "application/x-www-form-urlencoded; charset=UTF-8",
HTTP_HEADER_X_REQUESTED_WITH: "XMLHttpRequest",
REFERER: "http://{}/".format(self.host),
REFERER: f"http://{self.host}/",
CONNECTION: KEEP_ALIVE,
PRAGMA: 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
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}

View File

@ -24,7 +24,7 @@ from .const import (
_LOGGER = logging.getLogger(__name__)
TRACKER_UPDATE = "{}_tracker_update".format(DOMAIN)
TRACKER_UPDATE = f"{DOMAIN}_tracker_update"
DEFAULT_ACCURACY = 200
@ -83,7 +83,7 @@ async def handle_webhook(hass, webhook_id, request):
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):

View File

@ -57,7 +57,7 @@ class TradfriGroup(Light):
def __init__(self, group, api, gateway_id):
"""Initialize a Group."""
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._name = group.name
@ -152,7 +152,7 @@ class TradfriLight(Light):
def __init__(self, light, api, gateway_id):
"""Initialize a Light."""
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_control = None
self._light_data = None

View File

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

View File

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

View File

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

View File

@ -84,7 +84,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
for repo in repositories:
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):
sensors.append(TravisCISensor(travis, repo, user, branch, sensor_type))

View File

@ -40,28 +40,28 @@ async def async_setup_entry(
TwenteMilieuSensor(
twentemilieu,
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,
icon="mdi:delete-empty",
),
TwenteMilieuSensor(
twentemilieu,
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,
icon="mdi:delete-empty",
),
TwenteMilieuSensor(
twentemilieu,
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,
icon="mdi:delete-empty",
),
TwenteMilieuSensor(
twentemilieu,
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,
icon="mdi:delete-empty",
),
@ -110,7 +110,7 @@ class TwenteMilieuSensor(Entity):
@property
def unique_id(self) -> str:
"""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
def should_poll(self) -> bool:

View File

@ -11,7 +11,7 @@ CONF_AUTH_TOKEN = "auth_token"
DATA_TWILIO = DOMAIN
RECEIVED_DATA = "{}_data_received".format(DOMAIN)
RECEIVED_DATA = f"{DOMAIN}_data_received"
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.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.hostapd = []

View File

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

View File

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

View File

@ -69,7 +69,7 @@ def update_items(controller, async_add_entities, switches, switches_off):
# block client
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:
LOGGER.debug(
@ -91,7 +91,7 @@ def update_items(controller, async_add_entities, switches, switches_off):
# control poe
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:
LOGGER.debug(
@ -194,7 +194,7 @@ class UniFiPOEClientSwitch(UniFiClient, SwitchDevice, RestoreEntity):
@property
def unique_id(self):
"""Return a unique identifier for this switch."""
return "poe-{}".format(self.client.mac)
return f"poe-{self.client.mac}"
@property
def is_on(self):
@ -255,7 +255,7 @@ class UniFiBlockClientSwitch(UniFiClient, SwitchDevice):
@property
def unique_id(self):
"""Return a unique identifier for this switch."""
return "block-{}".format(self.client.mac)
return f"block-{self.client.mac}"
@property
def is_on(self):

View File

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

View File

@ -118,7 +118,7 @@ class RawUPnPIGDSensor(UpnpSensor):
@property
def unique_id(self) -> str:
"""Return an unique ID."""
return "{}_{}".format(self._device.udn, self._type_name)
return f"{self._device.udn}_{self._type_name}"
@property
def state(self) -> str:
@ -172,12 +172,12 @@ class PerSecondUPnPIGDSensor(UpnpSensor):
@property
def unique_id(self) -> str:
"""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
def name(self) -> str:
"""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
def icon(self) -> str:
@ -187,7 +187,7 @@ class PerSecondUPnPIGDSensor(UpnpSensor):
@property
def unit_of_measurement(self) -> str:
"""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:
"""Check if value has overflowed."""

View File

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

View File

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

View File

@ -152,7 +152,7 @@ class ValloxStateProxy:
raise OSError("Device state out of sync.")
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]

View File

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

View File

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

View File

@ -125,7 +125,7 @@ class Volumio(MediaPlayerDevice):
async def send_volumio_msg(self, method, params=None):
"""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)
@ -202,7 +202,7 @@ class Volumio(MediaPlayerDevice):
if str(url[0:2]).lower() == "ht":
mediaurl = url
else:
mediaurl = "http://{}:{}{}".format(self.host, self.port, url)
mediaurl = f"http://{self.host}:{self.port}{url}"
return mediaurl
@property

View File

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

View File

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

View File

@ -175,7 +175,7 @@ class WazeTravelTime(Entity):
return _get_location_from_attributes(state)
# 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):
_LOGGER.debug(
"%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):
"""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):
"""Determine setup.xml url for given host and port pair."""
@ -118,7 +118,7 @@ async def async_setup_entry(hass, entry):
if not port:
return None
return "http://{}:{}/setup.xml".format(host, port)
return f"http://{host}:{port}/setup.xml"
def discovery_dispatch(service, discovery_info):
"""Dispatcher for incoming WeMo discovery events."""
@ -150,7 +150,7 @@ async def async_setup_entry(hass, entry):
if not url:
_LOGGER.error(
"Unable to get description url for WeMo at: %s",
"{}:{}".format(host, port) if port else host,
f"{host}:{port}" if port else host,
)
continue

View File

@ -52,7 +52,7 @@ ATTR_HUB_NAME = "hub_name"
WINK_AUTH_CALLBACK_PATH = "/auth/wink/callback"
WINK_AUTH_START = "/auth/wink"
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"}
@ -228,7 +228,7 @@ def _request_app_setup(hass, config):
_configurator = hass.data[DOMAIN]["configuring"][DOMAIN]
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
https://developer.wink.com.
@ -268,9 +268,9 @@ def _request_oauth_completion(hass, config):
"""Call setup again."""
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(
DOMAIN, wink_configuration_callback, description=description

View File

@ -140,7 +140,7 @@ class WinkHub(WinkBinarySensorDevice):
# The service call to set the Kidde code
# takes a string of 1s and 0s so it makes
# 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
return _attributes

View File

@ -74,14 +74,14 @@ class WirelessTagPlatform:
def arm(self, switch):
"""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)
if arm_func is not None:
arm_func(switch.tag_id, switch.tag_manager_mac)
def disarm(self, switch):
"""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)
if disarm_func is not None:
disarm_func(switch.tag_id, switch.tag_manager_mac)
@ -132,18 +132,18 @@ class WirelessTagPlatform:
port = self.hass.config.api.port
if port is not None:
self._local_base_url += ":{}".format(port)
self._local_base_url += f":{port}"
return self._local_base_url
@property
def update_callback_url(self):
"""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
def binary_event_callback_url(self):
"""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):
"""Handle push event from wireless tag manager."""
@ -254,7 +254,7 @@ class WirelessTagBaseSensor(Entity):
# pylint: disable=no-self-use
def decorate_value(self, value):
"""Decorate input value to be well presented for end user."""
return "{:.1f}".format(value)
return f"{value:.1f}"
@property
def available(self):
@ -280,8 +280,8 @@ class WirelessTagBaseSensor(Entity):
"""Return the state attributes."""
return {
ATTR_BATTERY_LEVEL: int(self._tag.battery_remaining * 100),
ATTR_VOLTAGE: "{:.2f}V".format(self._tag.battery_volts),
ATTR_TAG_SIGNAL_STRENGTH: "{}dBm".format(self._tag.signal_strength),
ATTR_VOLTAGE: f"{self._tag.battery_volts:.2f}V",
ATTR_TAG_SIGNAL_STRENGTH: f"{self._tag.signal_strength}dBm",
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."""
super().__init__(api, tag)
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):
"""Register callbacks."""

View File

@ -79,5 +79,5 @@ class WirelessTagSwitch(WirelessTagBaseSensor, SwitchDevice):
@property
def principal_value(self):
"""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)

View File

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

View File

@ -96,12 +96,12 @@ class WorldTidesInfoSensor(Entity):
tidetime = time.strftime(
"%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"]):
tidetime = time.strftime(
"%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

View File

@ -63,12 +63,12 @@ class WorxLandroidSensor(Entity):
self.pin = config.get(CONF_PIN)
self.timeout = config.get(CONF_TIMEOUT)
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
def name(self):
"""Return the name of the sensor."""
return "worxlandroid-{}".format(self.sensor)
return f"worxlandroid-{self.sensor}"
@property
def state(self):

View File

@ -968,7 +968,7 @@ async def async_setup_platform(
)
if pws_id is None:
unique_id_base = "@{:06f},{:06f}".format(longitude, latitude)
unique_id_base = f"@{longitude:06f},{latitude:06f}"
else:
# Manually specified weather station, use that for unique_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
# the entity registry later.
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")
def _cfg_expand(self, what, default=None):
@ -1106,7 +1106,7 @@ class WUndergroundData:
self._hass = hass
self._api_key = api_key
self._pws_id = pws_id
self._lang = "lang:{}".format(lang)
self._lang = f"lang:{lang}"
self._latitude = latitude
self._longitude = longitude
self._features = set()
@ -1122,9 +1122,9 @@ class WUndergroundData:
self._api_key, "/".join(sorted(self._features)), self._lang
)
if self._pws_id:
url = url + "pws:{}".format(self._pws_id)
url = url + f"pws:{self._pws_id}"
else:
url = url + "{},{}".format(self._latitude, self._longitude)
url = url + f"{self._latitude},{self._longitude}"
return url + ".json"

View File

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