Use literal string interpolation in integrations B-D (f-strings) (#26378)

This commit is contained in:
Franck Nijhof 2019-09-03 17:09:59 +02:00 committed by Pascal Vizeli
parent 105461edb5
commit 6a24d893c8
52 changed files with 116 additions and 126 deletions

View File

@ -91,7 +91,7 @@ class BboxSensor(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

@ -99,7 +99,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
devices = []
for zone_id, extra in config[CONF_ZONES].items():
_LOGGER.info("Adding zone %d - %s", zone_id, extra[CONF_NAME])
unique_id = "{}-{}".format(connection, zone_id)
unique_id = f"{connection}-{zone_id}"
device = BlackbirdZone(blackbird, sources, zone_id, extra[CONF_NAME])
hass.data[DATA_BLACKBIRD][unique_id] = device
devices.append(device)

View File

@ -55,7 +55,7 @@ class BlinkSyncModule(AlarmControlPanel):
@property
def name(self):
"""Return the name of the panel."""
return "{} {}".format(BLINK_DATA, self._name)
return f"{BLINK_DATA} {self._name}"
@property
def device_state_attributes(self):

View File

@ -26,11 +26,11 @@ class BlinkBinarySensor(BinarySensorDevice):
self.data = data
self._type = sensor_type
name, icon = BINARY_SENSORS[sensor_type]
self._name = "{} {} {}".format(BLINK_DATA, camera, name)
self._name = f"{BLINK_DATA} {camera} {name}"
self._icon = icon
self._camera = data.cameras[camera]
self._state = None
self._unique_id = "{}-{}".format(self._camera.serial, self._type)
self._unique_id = f"{self._camera.serial}-{self._type}"
@property
def name(self):

View File

@ -30,9 +30,9 @@ class BlinkCamera(Camera):
"""Initialize a camera."""
super().__init__()
self.data = data
self._name = "{} {}".format(BLINK_DATA, name)
self._name = f"{BLINK_DATA} {name}"
self._camera = camera
self._unique_id = "{}-camera".format(camera.serial)
self._unique_id = f"{camera.serial}-camera"
self.response = None
self.current_image = None
self.last_image = None

View File

@ -28,7 +28,7 @@ class BlinkSensor(Entity):
def __init__(self, data, camera, sensor_type):
"""Initialize sensors from Blink camera."""
name, units, icon = SENSORS[sensor_type]
self._name = "{} {} {}".format(BLINK_DATA, camera, name)
self._name = f"{BLINK_DATA} {camera} {name}"
self._camera_name = name
self._type = sensor_type
self.data = data
@ -36,7 +36,7 @@ class BlinkSensor(Entity):
self._state = None
self._unit_of_measurement = units
self._icon = icon
self._unique_id = "{}-{}".format(self._camera.serial, self._type)
self._unique_id = f"{self._camera.serial}-{self._type}"
self._sensor_key = self._type
if self._type == "temperature":
self._sensor_key = "temperature_calibrated"

View File

@ -51,7 +51,7 @@ class BlinktLight(Light):
Default brightness and white color.
"""
self._blinkt = blinkt
self._name = "{}_{}".format(name, index)
self._name = f"{name}_{index}"
self._index = index
self._is_on = False
self._brightness = 255

View File

@ -63,7 +63,7 @@ class BloomSky:
"""Use the API to retrieve a list of devices."""
_LOGGER.debug("Fetching BloomSky update")
response = requests.get(
"{}?{}".format(self.API_URL, self._endpoint_argument),
f"{self.API_URL}?{self._endpoint_argument}",
headers={AUTHORIZATION: self._api_key},
timeout=10,
)

View File

@ -42,7 +42,7 @@ class BloomSkySensor(BinarySensorDevice):
self._sensor_name = sensor_name
self._name = "{} {}".format(device["DeviceName"], sensor_name)
self._state = None
self._unique_id = "{}-{}".format(self._device_id, self._sensor_name)
self._unique_id = f"{self._device_id}-{self._sensor_name}"
@property
def unique_id(self):

View File

@ -72,7 +72,7 @@ class BloomSkySensor(Entity):
self._sensor_name = sensor_name
self._name = "{} {}".format(device["DeviceName"], sensor_name)
self._state = None
self._unique_id = "{}-{}".format(self._device_id, self._sensor_name)
self._unique_id = f"{self._device_id}-{self._sensor_name}"
@property
def unique_id(self):
@ -103,6 +103,6 @@ class BloomSkySensor(Entity):
state = self._bloomsky.devices[self._device_id]["Data"][self._sensor_name]
if self._sensor_name in FORMAT_NUMBERS:
self._state = "{0:.2f}".format(state)
self._state = f"{state:.2f}"
else:
self._state = state

View File

@ -336,7 +336,7 @@ class BluesoundPlayer(MediaPlayerDevice):
if method[0] == "/":
method = method[1:]
url = "http://{}:{}/{}".format(self.host, self.port, method)
url = f"http://{self.host}:{self.port}/{method}"
_LOGGER.debug("Calling URL: %s", url)
response = None
@ -380,8 +380,8 @@ class BluesoundPlayer(MediaPlayerDevice):
etag = self._status.get("@etag", "")
if etag != "":
url = "Status?etag={}&timeout=120.0".format(etag)
url = "http://{}:{}/{}".format(self.host, self.port, url)
url = f"Status?etag={etag}&timeout=120.0"
url = f"http://{self.host}:{self.port}/{url}"
_LOGGER.debug("Calling URL: %s", url)
@ -595,7 +595,7 @@ class BluesoundPlayer(MediaPlayerDevice):
if not url:
return
if url[0] == "/":
url = "http://{}:{}{}".format(self.host, self.port, url)
url = f"http://{self.host}:{self.port}{url}"
return url
@ -843,13 +843,13 @@ class BluesoundPlayer(MediaPlayerDevice):
async def async_add_slave(self, slave_device):
"""Add slave to master."""
return await self.send_bluesound_command(
"/AddSlave?slave={}&port={}".format(slave_device.host, slave_device.port)
f"/AddSlave?slave={slave_device.host}&port={slave_device.port}"
)
async def async_remove_slave(self, slave_device):
"""Remove slave to master."""
return await self.send_bluesound_command(
"/RemoveSlave?slave={}&port={}".format(slave_device.host, slave_device.port)
f"/RemoveSlave?slave={slave_device.host}&port={slave_device.port}"
)
async def async_increase_timer(self):
@ -870,7 +870,7 @@ class BluesoundPlayer(MediaPlayerDevice):
async def async_set_shuffle(self, shuffle):
"""Enable or disable shuffle mode."""
value = "1" if shuffle else "0"
return await self.send_bluesound_command("/Shuffle?state={}".format(value))
return await self.send_bluesound_command(f"/Shuffle?state={value}")
async def async_select_source(self, source):
"""Select input source."""
@ -967,7 +967,7 @@ class BluesoundPlayer(MediaPlayerDevice):
if self.is_grouped and not self.is_master:
return
url = "Play?url={}".format(media_id)
url = f"Play?url={media_id}"
if kwargs.get(ATTR_MEDIA_ENQUEUE):
return await self.send_bluesound_command(url)

View File

@ -54,7 +54,7 @@ def setup_scanner(hass, config, see, discovery_info=None):
if rssi is not None:
attributes["rssi"] = rssi
see(
mac="{}{}".format(BT_PREFIX, mac),
mac=f"{BT_PREFIX}{mac}",
host_name=name,
attributes=attributes,
source_type=SOURCE_TYPE_BLUETOOTH,

View File

@ -147,7 +147,7 @@ class BME280Sensor(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

@ -331,7 +331,7 @@ class BME680Sensor(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

@ -61,8 +61,8 @@ class BMWConnectedDriveSensor(BinarySensorDevice):
self._account = account
self._vehicle = vehicle
self._attribute = attribute
self._name = "{} {}".format(self._vehicle.name, self._attribute)
self._unique_id = "{}-{}".format(self._vehicle.vin, self._attribute)
self._name = f"{self._vehicle.name} {self._attribute}"
self._unique_id = f"{self._vehicle.vin}-{self._attribute}"
self._sensor_name = sensor_name
self._device_class = device_class
self._icon = icon
@ -177,16 +177,14 @@ class BMWConnectedDriveSensor(BinarySensorDevice):
def _format_cbs_report(self, report):
result = {}
service_type = report.service_type.lower().replace("_", " ")
result["{} status".format(service_type)] = report.state.value
result[f"{service_type} status"] = report.state.value
if report.due_date is not None:
result["{} date".format(service_type)] = report.due_date.strftime(
"%Y-%m-%d"
)
result[f"{service_type} date"] = report.due_date.strftime("%Y-%m-%d")
if report.due_distance is not None:
distance = round(
self.hass.config.units.length(report.due_distance, LENGTH_KILOMETERS)
)
result["{} distance".format(service_type)] = "{} {}".format(
result[f"{service_type} distance"] = "{} {}".format(
distance, self.hass.config.units.length_unit
)
return result

View File

@ -30,8 +30,8 @@ class BMWLock(LockDevice):
self._account = account
self._vehicle = vehicle
self._attribute = attribute
self._name = "{} {}".format(self._vehicle.name, self._attribute)
self._unique_id = "{}-{}".format(self._vehicle.vin, self._attribute)
self._name = f"{self._vehicle.name} {self._attribute}"
self._unique_id = f"{self._vehicle.vin}-{self._attribute}"
self._sensor_name = sensor_name
self._state = None

View File

@ -68,8 +68,8 @@ class BMWConnectedDriveSensor(Entity):
self._account = account
self._attribute = attribute
self._state = None
self._name = "{} {}".format(self._vehicle.name, self._attribute)
self._unique_id = "{}-{}".format(self._vehicle.vin, self._attribute)
self._name = f"{self._vehicle.name} {self._attribute}"
self._unique_id = f"{self._vehicle.vin}-{self._attribute}"
self._attribute_info = attribute_info
@property

View File

@ -84,7 +84,7 @@ def _validate_schema(config):
LOCATIONS_MSG = "Set '{}' to one of: {}".format(
CONF_LOCATION, ", ".join(sorted(LOCATIONS))
)
XOR_MSG = "Specify exactly one of '{}' or '{}'".format(CONF_ID, CONF_LOCATION)
XOR_MSG = f"Specify exactly one of '{CONF_ID}' or '{CONF_LOCATION}'"
PLATFORM_SCHEMA = vol.All(
PLATFORM_SCHEMA.extend(
@ -106,7 +106,7 @@ PLATFORM_SCHEMA = vol.All(
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up BOM radar-loop camera component."""
location = config.get(CONF_LOCATION) or "ID {}".format(config.get(CONF_ID))
name = config.get(CONF_NAME) or "BOM Radar Loop - {}".format(location)
name = config.get(CONF_NAME) or f"BOM Radar Loop - {location}"
args = [
config.get(x)
for x in (CONF_LOCATION, CONF_ID, CONF_DELTA, CONF_FRAMES, CONF_OUTFILE)

View File

@ -117,7 +117,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
CONF_WMO_ID,
)
elif zone_id and wmo_id:
station = "{}.{}".format(zone_id, wmo_id)
station = f"{zone_id}.{wmo_id}"
else:
station = closest_station(
config.get(CONF_LATITUDE),

View File

@ -64,7 +64,7 @@ def async_setup_service(hass, host, device):
packet = await hass.async_add_executor_job(device.check_data)
if packet:
data = b64encode(packet).decode("utf8")
log_msg = "Received packet is: {}".format(data)
log_msg = f"Received packet is: {data}"
_LOGGER.info(log_msg)
hass.components.persistent_notification.async_create(
log_msg, title="Broadlink switch"

View File

@ -103,9 +103,9 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
def _get_mp1_slot_name(switch_friendly_name, slot):
"""Get slot name."""
if not slots["slot_{}".format(slot)]:
return "{} slot {}".format(switch_friendly_name, slot)
return slots["slot_{}".format(slot)]
if not slots[f"slot_{slot}"]:
return f"{switch_friendly_name} slot {slot}"
return slots[f"slot_{slot}"]
if switch_type in RM_TYPES:
broadlink_device = broadlink.rm((ip_addr, 80), mac_addr, None)
@ -371,7 +371,7 @@ class BroadlinkMP1Switch:
"""Get status of outlet from cached status list."""
if self._states is None:
return None
return self._states["s{}".format(slot)]
return self._states[f"s{slot}"]
@Throttle(TIME_BETWEEN_UPDATES)
def update(self):

View File

@ -401,7 +401,7 @@ class BrSensor(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

@ -134,7 +134,7 @@ async def async_request_stream(hass, entity_id, fmt):
if not source:
raise HomeAssistantError(
"{} does not support play stream service".format(camera.entity_id)
f"{camera.entity_id} does not support play stream service"
)
return request_stream(hass, source, fmt=fmt, keepalive=camera_prefs.preload_stream)
@ -534,9 +534,7 @@ class CameraMjpegStream(CameraView):
# Compose camera stream from stills
interval = float(request.query.get("interval"))
if interval < MIN_STREAM_INTERVAL:
raise ValueError(
"Stream interval must be be > {}".format(MIN_STREAM_INTERVAL)
)
raise ValueError(f"Stream interval must be be > {MIN_STREAM_INTERVAL}")
return await camera.handle_async_still_stream(request, interval)
except ValueError:
raise web.HTTPBadRequest()
@ -588,7 +586,7 @@ async def ws_camera_stream(hass, connection, msg):
if not source:
raise HomeAssistantError(
"{} does not support play stream service".format(camera.entity_id)
f"{camera.entity_id} does not support play stream service"
)
fmt = msg["format"]
@ -670,7 +668,7 @@ async def async_handle_play_stream_service(camera, service_call):
if not source:
raise HomeAssistantError(
"{} does not support play stream service".format(camera.entity_id)
f"{camera.entity_id} does not support play stream service"
)
hass = camera.hass
@ -681,7 +679,7 @@ async def async_handle_play_stream_service(camera, service_call):
url = request_stream(hass, source, fmt=fmt, keepalive=camera_prefs.preload_stream)
data = {
ATTR_ENTITY_ID: entity_ids,
ATTR_MEDIA_CONTENT_ID: "{}{}".format(hass.config.api.base_url, url),
ATTR_MEDIA_CONTENT_ID: f"{hass.config.api.base_url}{url}",
ATTR_MEDIA_CONTENT_TYPE: FORMAT_CONTENT_TYPE[fmt],
}
@ -696,9 +694,7 @@ async def async_handle_record_service(camera, call):
source = await camera.stream_source()
if not source:
raise HomeAssistantError(
"{} does not support record service".format(camera.entity_id)
)
raise HomeAssistantError(f"{camera.entity_id} does not support record service")
hass = camera.hass
filename = call.data[CONF_FILENAME]

View File

@ -53,7 +53,7 @@ class CanarySensor(Entity):
self._sensor_value = None
sensor_type_name = sensor_type[0].replace("_", " ").title()
self._name = "{} {} {}".format(location.name, device.name, sensor_type_name)
self._name = f"{location.name} {device.name} {sensor_type_name}"
@property
def name(self):

View File

@ -52,9 +52,7 @@ class CiscoWebexTeamsNotificationService(BaseNotificationService):
title = "{}{}".format(kwargs.get(ATTR_TITLE), "<br>")
try:
self.client.messages.create(
roomId=self.room, html="{}{}".format(title, message)
)
self.client.messages.create(roomId=self.room, html=f"{title}{message}")
except ApiError as api_error:
_LOGGER.error(
"Could not send CiscoWebexTeams notification. " "Error: %s", api_error

View File

@ -73,7 +73,7 @@ class ClicksendNotificationService(BaseNotificationService):
}
)
api_url = "{}/sms/send".format(BASE_API_URL)
api_url = f"{BASE_API_URL}/sms/send"
resp = requests.post(
api_url,
data=json.dumps(data),
@ -94,7 +94,7 @@ class ClicksendNotificationService(BaseNotificationService):
def _authenticate(config):
"""Authenticate with ClickSend."""
api_url = "{}/account".format(BASE_API_URL)
api_url = f"{BASE_API_URL}/account"
resp = requests.get(
api_url,
headers=HEADERS,

View File

@ -79,7 +79,7 @@ class ClicksendNotificationService(BaseNotificationService):
}
]
}
api_url = "{}/voice/send".format(BASE_API_URL)
api_url = f"{BASE_API_URL}/voice/send"
resp = requests.post(
api_url,
data=json.dumps(data),
@ -100,7 +100,7 @@ class ClicksendNotificationService(BaseNotificationService):
def _authenticate(config):
"""Authenticate with ClickSend."""
api_url = "{}/account".format(BASE_API_URL)
api_url = f"{BASE_API_URL}/account"
resp = requests.get(
api_url,
headers=HEADERS,

View File

@ -157,7 +157,7 @@ def _process_cloud_exception(exc, where):
err_info = _CLOUD_ERRORS.get(exc.__class__)
if err_info is None:
_LOGGER.exception("Unexpected error processing request for %s", where)
err_info = (502, "Unexpected error: {}".format(exc))
err_info = (502, f"Unexpected error: {exc}")
return err_info

View File

@ -82,7 +82,7 @@ class CmusDevice(MediaPlayerDevice):
if server:
self.cmus = remote.PyCmus(server=server, password=password, port=port)
auto_name = "cmus-{}".format(server)
auto_name = f"cmus-{server}"
else:
self.cmus = remote.PyCmus()
auto_name = "cmus-local"

View File

@ -68,7 +68,7 @@ class CO2Sensor(Entity):
lat=round(self._latitude, 2), lon=round(self._longitude, 2)
)
self._friendly_name = "CO2 intensity - {}".format(device_name)
self._friendly_name = f"CO2 intensity - {device_name}"
@property
def name(self):

View File

@ -44,7 +44,7 @@ class AccountSensor(Entity):
def __init__(self, coinbase_data, name, currency):
"""Initialize the sensor."""
self._coinbase_data = coinbase_data
self._name = "Coinbase {}".format(name)
self._name = f"Coinbase {name}"
self._state = None
self._unit_of_measurement = currency
self._native_balance = None
@ -97,7 +97,7 @@ class ExchangeRateSensor(Entity):
"""Initialize the sensor."""
self._coinbase_data = coinbase_data
self.currency = exchange_currency
self._name = "{} Exchange Rate".format(exchange_currency)
self._name = f"{exchange_currency} Exchange Rate"
self._state = None
self._unit_of_measurement = native_currency

View File

@ -47,7 +47,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
host = config.get(CONF_HOST)
port = config.get(CONF_PORT)
url = "http://{}:{}".format(host, port)
url = f"http://{host}:{port}"
try:
add_entities([Concord232Alarm(url, name, code, mode)], True)

View File

@ -51,7 +51,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
try:
_LOGGER.debug("Initializing client")
client = concord232_client.Client("http://{}:{}".format(host, port))
client = concord232_client.Client(f"http://{host}:{port}")
client.zones = client.list_zones()
client.last_zone_update = datetime.datetime.now()

View File

@ -29,7 +29,7 @@ _LOGGER = logging.getLogger(__name__)
DOMAIN = "crimereports"
EVENT_INCIDENT = "{}_incident".format(DOMAIN)
EVENT_INCIDENT = f"{DOMAIN}_incident"
SCAN_INTERVAL = timedelta(minutes=30)

View File

@ -333,7 +333,7 @@ class CupsData:
else:
for ipp_printer in self._ipp_printers:
self.attributes[ipp_printer] = conn.getPrinterAttributes(
uri="ipp://{}:{}/{}".format(self._host, self._port, ipp_printer)
uri=f"ipp://{self._host}:{self._port}/{ipp_printer}"
)
self.available = True

View File

@ -95,7 +95,7 @@ class CurrencylayerSensor(Entity):
self.rest.update()
value = self.rest.data
if value is not None:
self._state = round(value["{}{}".format(self._base, self._quote)], 4)
self._state = round(value[f"{self._base}{self._quote}"], 4)
class CurrencylayerData:

View File

@ -58,7 +58,7 @@ class DaikinClimateSensor(Entity):
@property
def unique_id(self):
"""Return a unique ID."""
return "{}-{}".format(self._api.mac, self._device_attribute)
return f"{self._api.mac}-{self._device_attribute}"
@property
def icon(self):

View File

@ -44,7 +44,7 @@ class DaikinZoneSwitch(ToggleEntity):
@property
def unique_id(self):
"""Return a unique ID."""
return "{}-zone{}".format(self._api.mac, self._zone_id)
return f"{self._api.mac}-zone{self._zone_id}"
@property
def icon(self):

View File

@ -553,10 +553,10 @@ class DarkSkySensor(Entity):
def name(self):
"""Return the name of the sensor."""
if self.forecast_day is not None:
return "{} {} {}d".format(self.client_name, self._name, self.forecast_day)
return f"{self.client_name} {self._name} {self.forecast_day}d"
if self.forecast_hour is not None:
return "{} {} {}h".format(self.client_name, self._name, self.forecast_hour)
return "{} {}".format(self.client_name, self._name)
return f"{self.client_name} {self._name} {self.forecast_hour}h"
return f"{self.client_name} {self._name}"
@property
def state(self):
@ -704,7 +704,7 @@ class DarkSkyAlertSensor(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

@ -59,7 +59,7 @@ def setup(hass, config):
statsd.event(
title="Home Assistant",
text="%%% \n **{}** {} \n %%%".format(name, message),
text=f"%%% \n **{name}** {message} \n %%%",
tags=[
"entity:{}".format(event.data.get("entity_id")),
"domain:{}".format(event.data.get("domain")),
@ -79,8 +79,8 @@ def setup(hass, config):
return
states = dict(state.attributes)
metric = "{}.{}".format(prefix, state.domain)
tags = ["entity:{}".format(state.entity_id)]
metric = f"{prefix}.{state.domain}"
tags = [f"entity:{state.entity_id}"]
for key, value in states.items():
if isinstance(value, (float, int)):

View File

@ -65,7 +65,7 @@ class DdWrtDeviceScanner(DeviceScanner):
self.mac2name = {}
# Test the router is accessible
url = "{}://{}/Status_Wireless.live.asp".format(self.protocol, self.host)
url = f"{self.protocol}://{self.host}/Status_Wireless.live.asp"
data = self.get_ddwrt_data(url)
if not data:
raise ConnectionError("Cannot connect to DD-Wrt router")
@ -80,7 +80,7 @@ class DdWrtDeviceScanner(DeviceScanner):
"""Return the name of the given device or None if we don't know."""
# If not initialised and not already scanned and not found.
if device not in self.mac2name:
url = "{}://{}/Status_Lan.live.asp".format(self.protocol, self.host)
url = f"{self.protocol}://{self.host}/Status_Lan.live.asp"
data = self.get_ddwrt_data(url)
if not data:
@ -115,7 +115,7 @@ class DdWrtDeviceScanner(DeviceScanner):
_LOGGER.info("Checking ARP")
endpoint = "Wireless" if self.wireless_only else "Lan"
url = "{}://{}/Status_{}.live.asp".format(self.protocol, self.host, endpoint)
url = f"{self.protocol}://{self.host}/Status_{endpoint}.live.asp"
data = self.get_ddwrt_data(url)
if not data:

View File

@ -138,7 +138,7 @@ class DeconzGateway:
@property
def event_reachable(self):
"""Gateway specific event to signal a change in connection status."""
return "deconz_reachable_{}".format(self.bridgeid)
return f"deconz_reachable_{self.bridgeid}"
@callback
def async_connection_status_callback(self, available):
@ -241,7 +241,7 @@ class DeconzEvent:
self._hass = hass
self._device = device
self._device.register_async_callback(self.async_update_callback)
self._event = "deconz_{}".format(CONF_EVENT)
self._event = f"deconz_{CONF_EVENT}"
self._id = slugify(self._device.name)
_LOGGER.debug("deCONZ event created: %s", self._id)

View File

@ -84,7 +84,7 @@ class DelugeSensor(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

@ -47,7 +47,7 @@ class DeutscheBahnSensor(Entity):
def __init__(self, start, goal, offset, only_direct):
"""Initialize the sensor."""
self._name = "{} to {}".format(start, goal)
self._name = f"{start} to {goal}"
self.data = SchieneData(start, goal, offset, only_direct)
self._state = None

View File

@ -115,7 +115,7 @@ class DHTSensor(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

@ -88,7 +88,7 @@ class DINRelay(SwitchDevice):
@property
def name(self):
"""Return the display name of this relay."""
return "{}_{}".format(self._controller_name, self._name)
return f"{self._controller_name}_{self._name}"
@property
def is_on(self):

View File

@ -20,7 +20,7 @@ _LOGGER = logging.getLogger(__name__)
DOMAIN = "doorbird"
API_URL = "/api/{}".format(DOMAIN)
API_URL = f"/api/{DOMAIN}"
CONF_CUSTOM_URL = "hass_url_override"
CONF_EVENTS = "events"
@ -195,17 +195,15 @@ class ConfiguredDoorBird:
return slugify(self._name)
def _get_event_name(self, event):
return "{}_{}".format(self.slug, event)
return f"{self.slug}_{event}"
def _register_event(self, hass_url, event):
"""Add a schedule entry in the device for a sensor."""
url = "{}{}/{}?token={}".format(hass_url, API_URL, event, self._token)
url = f"{hass_url}{API_URL}/{event}?token={self._token}"
# Register HA URL as webhook if not already, then get the ID
if not self.webhook_is_registered(url):
self.device.change_favorite(
"http", "Home Assistant ({})".format(event), url
)
self.device.change_favorite("http", f"Home Assistant ({event})", url)
fav_id = self.get_webhook_id(url)
@ -288,9 +286,9 @@ class DoorBirdRequestView(HomeAssistantView):
if event == "clear":
hass.bus.async_fire(RESET_DEVICE_FAVORITES, {"token": token})
message = "HTTP Favorites cleared for {}".format(device.slug)
message = f"HTTP Favorites cleared for {device.slug}"
return web.Response(status=200, text=message)
hass.bus.async_fire("{}_{}".format(DOMAIN, event), event_data)
hass.bus.async_fire(f"{DOMAIN}_{event}", event_data)
return web.Response(status=200, text="OK")

View File

@ -45,9 +45,9 @@ class DoorBirdSwitch(SwitchDevice):
def name(self):
"""Return the name of the switch."""
if self._relay == IR_RELAY:
return "{} IR".format(self._doorstation.name)
return f"{self._doorstation.name} IR"
return "{} Relay {}".format(self._doorstation.name, self._relay)
return f"{self._doorstation.name} Relay {self._relay}"
@property
def icon(self):

View File

@ -81,7 +81,7 @@ def setup(hass, config):
"downloading '%s' failed, status_code=%d", url, req.status_code
)
hass.bus.fire(
"{}_{}".format(DOMAIN, DOWNLOAD_FAILED_EVENT),
f"{DOMAIN}_{DOWNLOAD_FAILED_EVENT}",
{"url": url, "filename": filename},
)
@ -126,7 +126,7 @@ def setup(hass, config):
while os.path.isfile(final_path):
tries += 1
final_path = "{}_{}.{}".format(path, tries, ext)
final_path = f"{path}_{tries}.{ext}"
_LOGGER.debug("%s -> %s", url, final_path)
@ -136,14 +136,14 @@ def setup(hass, config):
_LOGGER.debug("Downloading of %s done", url)
hass.bus.fire(
"{}_{}".format(DOMAIN, DOWNLOAD_COMPLETED_EVENT),
f"{DOMAIN}_{DOWNLOAD_COMPLETED_EVENT}",
{"url": url, "filename": filename},
)
except requests.exceptions.ConnectionError:
_LOGGER.exception("ConnectionError occurred for %s", url)
hass.bus.fire(
"{}_{}".format(DOMAIN, DOWNLOAD_FAILED_EVENT),
f"{DOMAIN}_{DOWNLOAD_FAILED_EVENT}",
{"url": url, "filename": filename},
)

View File

@ -44,7 +44,7 @@ class DukeEnergyMeter(Entity):
@property
def name(self):
"""Return the name."""
return "duke_energy_{}".format(self.duke_meter.id)
return f"duke_energy_{self.duke_meter.id}"
@property
def unique_id(self):

View File

@ -92,7 +92,7 @@ class DwdWeatherWarningsSensor(Entity):
@property
def name(self):
"""Return the name of the sensor."""
return "{} {}".format(self._name, self._var_name)
return f"{self._name} {self._var_name}"
@property
def icon(self):
@ -140,23 +140,23 @@ class DwdWeatherWarningsSensor(Entity):
for event in self._api.data[prefix + "_warnings"]:
i = i + 1
data["warning_{}_name".format(i)] = event["event"]
data["warning_{}_level".format(i)] = event["level"]
data["warning_{}_type".format(i)] = event["type"]
data[f"warning_{i}_name"] = event["event"]
data[f"warning_{i}_level"] = event["level"]
data[f"warning_{i}_type"] = event["type"]
if event["headline"]:
data["warning_{}_headline".format(i)] = event["headline"]
data[f"warning_{i}_headline"] = event["headline"]
if event["description"]:
data["warning_{}_description".format(i)] = event["description"]
data[f"warning_{i}_description"] = event["description"]
if event["instruction"]:
data["warning_{}_instruction".format(i)] = event["instruction"]
data[f"warning_{i}_instruction"] = event["instruction"]
if event["start"] is not None:
data["warning_{}_start".format(i)] = dt_util.as_local(
data[f"warning_{i}_start"] = dt_util.as_local(
dt_util.utc_from_timestamp(event["start"] / 1000)
)
if event["end"] is not None:
data["warning_{}_end".format(i)] = dt_util.as_local(
data[f"warning_{i}_end"] = dt_util.as_local(
dt_util.utc_from_timestamp(event["end"] / 1000)
)
@ -212,7 +212,7 @@ class DwdWeatherWarningsAPI:
"Found %d %s global DWD warnings", len(json_obj[myvalue]), mykey
)
data["{}_warning_level".format(mykey)] = 0
data[f"{mykey}_warning_level"] = 0
my_warnings = []
if self.region_id is not None:
@ -234,13 +234,13 @@ class DwdWeatherWarningsAPI:
break
# Get max warning level
maxlevel = data["{}_warning_level".format(mykey)]
maxlevel = data[f"{mykey}_warning_level"]
for event in my_warnings:
if event["level"] >= maxlevel:
data["{}_warning_level".format(mykey)] = event["level"]
data[f"{mykey}_warning_level"] = event["level"]
data["{}_warning_count".format(mykey)] = len(my_warnings)
data["{}_warnings".format(mykey)] = my_warnings
data[f"{mykey}_warning_count"] = len(my_warnings)
data[f"{mykey}_warnings"] = my_warnings
_LOGGER.debug("Found %d %s local DWD warnings", len(my_warnings), mykey)

View File

@ -101,7 +101,7 @@ class DysonSensor(Entity):
@property
def unique_id(self):
"""Return the sensor's unique id."""
return "{}-{}".format(self._device.serial, self._sensor_type)
return f"{self._device.serial}-{self._sensor_type}"
class DysonFilterLifeSensor(DysonSensor):
@ -110,7 +110,7 @@ class DysonFilterLifeSensor(DysonSensor):
def __init__(self, device):
"""Create a new Dyson Filter Life sensor."""
super().__init__(device, "filter_life")
self._name = "{} Filter Life".format(self._device.name)
self._name = f"{self._device.name} Filter Life"
@property
def state(self):
@ -126,7 +126,7 @@ class DysonDustSensor(DysonSensor):
def __init__(self, device):
"""Create a new Dyson Dust sensor."""
super().__init__(device, "dust")
self._name = "{} Dust".format(self._device.name)
self._name = f"{self._device.name} Dust"
@property
def state(self):
@ -142,7 +142,7 @@ class DysonHumiditySensor(DysonSensor):
def __init__(self, device):
"""Create a new Dyson Humidity sensor."""
super().__init__(device, "humidity")
self._name = "{} Humidity".format(self._device.name)
self._name = f"{self._device.name} Humidity"
@property
def state(self):
@ -160,7 +160,7 @@ class DysonTemperatureSensor(DysonSensor):
def __init__(self, device, unit):
"""Create a new Dyson Temperature sensor."""
super().__init__(device, "temperature")
self._name = "{} Temperature".format(self._device.name)
self._name = f"{self._device.name} Temperature"
self._unit = unit
@property
@ -187,7 +187,7 @@ class DysonAirQualitySensor(DysonSensor):
def __init__(self, device):
"""Create a new Dyson Air Quality sensor."""
super().__init__(device, "air_quality")
self._name = "{} AQI".format(self._device.name)
self._name = f"{self._device.name} AQI"
@property
def state(self):