Use literal string interpolation in integrations R-S (f-strings) (#26392)

This commit is contained in:
Franck Nijhof 2019-09-03 21:14:39 +02:00 committed by Pascal Vizeli
parent 7203027cbf
commit 445c741b30
69 changed files with 129 additions and 149 deletions

View File

@ -226,7 +226,7 @@ class RachioIro:
def __str__(self) -> str: def __str__(self) -> str:
"""Display the controller as a string.""" """Display the controller as a string."""
return 'Rachio controller "{}"'.format(self.name) return f'Rachio controller "{self.name}"'
@property @property
def controller_id(self) -> str: def controller_id(self) -> str:

View File

@ -87,12 +87,12 @@ class RachioControllerOnlineBinarySensor(RachioControllerBinarySensor):
@property @property
def name(self) -> str: def name(self) -> str:
"""Return the name of this sensor including the controller name.""" """Return the name of this sensor including the controller name."""
return "{} online".format(self._controller.name) return f"{self._controller.name} online"
@property @property
def unique_id(self) -> str: def unique_id(self) -> str:
"""Return a unique id for this entity.""" """Return a unique id for this entity."""
return "{}-online".format(self._controller.controller_id) return f"{self._controller.controller_id}-online"
@property @property
def device_class(self) -> str: def device_class(self) -> str:

View File

@ -72,7 +72,7 @@ class RachioSwitch(SwitchDevice):
@property @property
def name(self) -> str: def name(self) -> str:
"""Get a name for this switch.""" """Get a name for this switch."""
return "Switch on {}".format(self._controller.name) return f"Switch on {self._controller.name}"
@property @property
def is_on(self) -> bool: def is_on(self) -> bool:
@ -113,12 +113,12 @@ class RachioStandbySwitch(RachioSwitch):
@property @property
def name(self) -> str: def name(self) -> str:
"""Return the name of the standby switch.""" """Return the name of the standby switch."""
return "{} in standby mode".format(self._controller.name) return f"{self._controller.name} in standby mode"
@property @property
def unique_id(self) -> str: def unique_id(self) -> str:
"""Return a unique id by combining controller id and purpose.""" """Return a unique id by combining controller id and purpose."""
return "{}-standby".format(self._controller.controller_id) return f"{self._controller.controller_id}-standby"
@property @property
def icon(self) -> str: def icon(self) -> str:
@ -183,7 +183,7 @@ class RachioZone(RachioSwitch):
@property @property
def unique_id(self) -> str: def unique_id(self) -> str:
"""Return a unique id by combining controller id and zone number.""" """Return a unique id by combining controller id and zone number."""
return "{}-zone-{}".format(self._controller.controller_id, self.zone_id) return f"{self._controller.controller_id}-zone-{self.zone_id}"
@property @property
def icon(self) -> str: def icon(self) -> str:

View File

@ -53,7 +53,7 @@ class RainBirdSwitch(SwitchDevice):
self._rainbird = rb self._rainbird = rb
self._devid = dev_id self._devid = dev_id
self._zone = int(dev.get(CONF_ZONE)) self._zone = int(dev.get(CONF_ZONE))
self._name = dev.get(CONF_FRIENDLY_NAME, "Sprinkler {}".format(self._zone)) self._name = dev.get(CONF_FRIENDLY_NAME, f"Sprinkler {self._zone}")
self._state = None self._state = None
self._duration = dev.get(CONF_TRIGGER_TIME) self._duration = dev.get(CONF_TRIGGER_TIME)
self._attributes = {"duration": self._duration, "zone": self._zone} self._attributes = {"duration": self._duration, "zone": self._zone}

View File

@ -41,9 +41,9 @@ _LOGGER = logging.getLogger(__name__)
DATA_LISTENER = "listener" DATA_LISTENER = "listener"
PROGRAM_UPDATE_TOPIC = "{0}_program_update".format(DOMAIN) PROGRAM_UPDATE_TOPIC = f"{DOMAIN}_program_update"
SENSOR_UPDATE_TOPIC = "{0}_data_update".format(DOMAIN) SENSOR_UPDATE_TOPIC = f"{DOMAIN}_data_update"
ZONE_UPDATE_TOPIC = "{0}_zone_update".format(DOMAIN) ZONE_UPDATE_TOPIC = f"{DOMAIN}_zone_update"
CONF_CONTROLLERS = "controllers" CONF_CONTROLLERS = "controllers"
CONF_PROGRAM_ID = "program_id" CONF_PROGRAM_ID = "program_id"

View File

@ -66,7 +66,7 @@ class RecollectWasteSensor(Entity):
@property @property
def unique_id(self) -> str: def unique_id(self) -> str:
"""Return a unique ID.""" """Return a unique ID."""
return "{}{}".format(self.client.place_id, self.client.service_id) return f"{self.client.place_id}{self.client.service_id}"
@property @property
def state(self): def state(self):

View File

@ -94,7 +94,7 @@ class RedditSensor(Entity):
@property @property
def name(self): def name(self):
"""Return the name of the sensor.""" """Return the name of the sensor."""
return "reddit_{}".format(self._subreddit) return f"reddit_{self._subreddit}"
@property @property
def state(self): def state(self):

View File

@ -220,7 +220,7 @@ class PublicTransportData:
and due_at_time is not None and due_at_time is not None
and route is not None and route is not None
): ):
due_at = "{} {}".format(due_at_date, due_at_time) due_at = f"{due_at_date} {due_at_time}"
departure_data = { departure_data = {
ATTR_DUE_IN: due_in_minutes(due_at), ATTR_DUE_IN: due_in_minutes(due_at),

View File

@ -87,13 +87,13 @@ def _create_instance(
component.add_entities([entity]) component.add_entities([entity])
hass.services.register( hass.services.register(
DOMAIN, DOMAIN,
"{}_create_task".format(account_name), f"{account_name}_create_task",
entity.create_task, entity.create_task,
schema=SERVICE_SCHEMA_CREATE_TASK, schema=SERVICE_SCHEMA_CREATE_TASK,
) )
hass.services.register( hass.services.register(
DOMAIN, DOMAIN,
"{}_complete_task".format(account_name), f"{account_name}_complete_task",
entity.complete_task, entity.complete_task,
schema=SERVICE_SCHEMA_COMPLETE_TASK, schema=SERVICE_SCHEMA_COMPLETE_TASK,
) )
@ -137,7 +137,7 @@ def _register_new_account(
configurator.request_done(request_id) configurator.request_done(request_id)
request_id = configurator.async_request_config( request_id = configurator.async_request_config(
"{} - {}".format(DOMAIN, account_name), f"{DOMAIN} - {account_name}",
callback=register_account_callback, callback=register_account_callback,
description="You need to log in to Remember The Milk to" description="You need to log in to Remember The Milk to"
+ "connect your account. \n\n" + "connect your account. \n\n"

View File

@ -239,7 +239,7 @@ class PrinterAPI:
info["name"] = printer.slug info["name"] = printer.slug
info["printer_name"] = self.conf_name info["printer_name"] = self.conf_name
known = "{}-{}".format(printer.slug, sensor_type) known = f"{printer.slug}-{sensor_type}"
if known in self._known_entities: if known in self._known_entities:
continue continue

View File

@ -300,7 +300,7 @@ class ToggleRflinkLight(SwitchableRflinkDevice, Light):
@property @property
def entity_id(self): def entity_id(self):
"""Return entity id.""" """Return entity id."""
return "light.{}".format(self.name) return f"light.{self.name}"
def _handle_event(self, event): def _handle_event(self, event):
"""Adjust state if Rflink picks up a remote command for this device.""" """Adjust state if Rflink picks up a remote command for this device."""

View File

@ -106,7 +106,7 @@ def setup(hass, config):
slugify(event.device.id_string.lower()), slugify(event.device.id_string.lower()),
event.device.__class__.__name__, event.device.__class__.__name__,
event.device.subtype, event.device.subtype,
"".join("{0:02x}".format(x) for x in event.data), "".join(f"{x:02x}" for x in event.data),
) )
# Callback to HA registered components. # Callback to HA registered components.
@ -270,7 +270,7 @@ def get_new_device(event, config, device):
if not config[ATTR_AUTOMATIC_ADD]: if not config[ATTR_AUTOMATIC_ADD]:
return return
pkt_id = "".join("{0:02x}".format(x) for x in event.data) pkt_id = "".join(f"{x:02x}" for x in event.data)
_LOGGER.debug( _LOGGER.debug(
"Automatic add %s rfxtrx device (Class: %s Sub: %s Packet_id: %s)", "Automatic add %s rfxtrx device (Class: %s Sub: %s Packet_id: %s)",
device_id, device_id,

View File

@ -116,7 +116,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
poss_id = slugify(poss_dev.event.device.id_string.lower()) poss_id = slugify(poss_dev.event.device.id_string.lower())
_LOGGER.debug("Found possible matching device ID: %s", poss_id) _LOGGER.debug("Found possible matching device ID: %s", poss_id)
pkt_id = "".join("{0:02x}".format(x) for x in event.data) pkt_id = "".join(f"{x:02x}" for x in event.data)
sensor = RfxtrxBinarySensor(event, pkt_id) sensor = RfxtrxBinarySensor(event, pkt_id)
sensor.hass = hass sensor.hass = hass
rfxtrx.RFX_DEVICES[device_id] = sensor rfxtrx.RFX_DEVICES[device_id] = sensor

View File

@ -98,7 +98,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
if not config[CONF_AUTOMATIC_ADD]: if not config[CONF_AUTOMATIC_ADD]:
return return
pkt_id = "".join("{0:02x}".format(x) for x in event.data) pkt_id = "".join(f"{x:02x}" for x in event.data)
_LOGGER.info("Automatic add rfxtrx.sensor: %s", pkt_id) _LOGGER.info("Automatic add rfxtrx.sensor: %s", pkt_id)
data_type = "" data_type = ""
@ -141,7 +141,7 @@ class RfxtrxSensor(Entity):
@property @property
def name(self): def name(self):
"""Get the name of the sensor.""" """Get the name of the sensor."""
return "{} {}".format(self._name, self.data_type) return f"{self._name} {self.data_type}"
@property @property
def device_state_attributes(self): def device_state_attributes(self):

View File

@ -73,7 +73,7 @@ class RingBinarySensor(BinarySensorDevice):
) )
self._device_class = SENSOR_TYPES.get(self._sensor_type)[2] self._device_class = SENSOR_TYPES.get(self._sensor_type)[2]
self._state = None self._state = None
self._unique_id = "{}-{}".format(self._data.id, self._sensor_type) self._unique_id = f"{self._data.id}-{self._sensor_type}"
@property @property
def name(self): def name(self):

View File

@ -56,7 +56,7 @@ class RingLight(Light):
@property @property
def name(self): def name(self):
"""Name of the light.""" """Name of the light."""
return "{} light".format(self._device.name) return f"{self._device.name} light"
@property @property
def unique_id(self): def unique_id(self):

View File

@ -121,7 +121,7 @@ class RingSensor(Entity):
) )
self._state = None self._state = None
self._tz = str(hass.config.time_zone) self._tz = str(hass.config.time_zone)
self._unique_id = "{}-{}".format(self._data.id, self._sensor_type) self._unique_id = f"{self._data.id}-{self._sensor_type}"
async def async_added_to_hass(self): async def async_added_to_hass(self):
"""Register callbacks.""" """Register callbacks."""

View File

@ -38,7 +38,7 @@ class BaseRingSwitch(SwitchDevice):
"""Initialize the switch.""" """Initialize the switch."""
self._device = device self._device = device
self._device_type = device_type self._device_type = device_type
self._unique_id = "{}-{}".format(self._device.id, self._device_type) self._unique_id = f"{self._device.id}-{self._device_type}"
async def async_added_to_hass(self): async def async_added_to_hass(self):
"""Register callbacks.""" """Register callbacks."""
@ -53,7 +53,7 @@ class BaseRingSwitch(SwitchDevice):
@property @property
def name(self): def name(self):
"""Name of the device.""" """Name of the device."""
return "{} {}".format(self._device.name, self._device_type) return f"{self._device.name} {self._device_type}"
@property @property
def unique_id(self): def unique_id(self):

View File

@ -78,7 +78,7 @@ def scan_for_rokus(hass):
"Name: {0}<br />Host: {1}<br />".format( "Name: {0}<br />Host: {1}<br />".format(
r_info.userdevicename r_info.userdevicename
if r_info.userdevicename if r_info.userdevicename
else "{} {}".format(r_info.modelname, r_info.serial_num), else f"{r_info.modelname} {r_info.serial_num}",
roku.host, roku.host,
) )
) )

View File

@ -92,7 +92,7 @@ class RokuDevice(MediaPlayerDevice):
"""Return the name of the device.""" """Return the name of the device."""
if self._device_info.user_device_name: if self._device_info.user_device_name:
return self._device_info.user_device_name return self._device_info.user_device_name
return "Roku {}".format(self._device_info.serial_num) return f"Roku {self._device_info.serial_num}"
@property @property
def state(self): def state(self):

View File

@ -36,7 +36,7 @@ class RokuRemote(remote.RemoteDevice):
"""Return the name of the device.""" """Return the name of the device."""
if self._device_info.user_device_name: if self._device_info.user_device_name:
return self._device_info.user_device_name return self._device_info.user_device_name
return "Roku {}".format(self._device_info.serial_num) return f"Roku {self._device_info.serial_num}"
@property @property
def unique_id(self): def unique_id(self):

View File

@ -327,7 +327,7 @@ class RoombaVacuum(VacuumDevice):
pos_y = pos_state.get("point", {}).get("y") pos_y = pos_state.get("point", {}).get("y")
theta = pos_state.get("theta") theta = pos_state.get("theta")
if all(item is not None for item in [pos_x, pos_y, theta]): if all(item is not None for item in [pos_x, pos_y, theta]):
position = "({}, {}, {})".format(pos_x, pos_y, theta) position = f"({pos_x}, {pos_y}, {theta})"
self._state_attrs[ATTR_POSITION] = position self._state_attrs[ATTR_POSITION] = position
# Not all Roombas have a bin full sensor # Not all Roombas have a bin full sensor

View File

@ -104,7 +104,7 @@ def _update_route53(
{ {
"Action": "UPSERT", "Action": "UPSERT",
"ResourceRecordSet": { "ResourceRecordSet": {
"Name": "{}.{}".format(record, domain), "Name": f"{record}.{domain}",
"Type": "A", "Type": "A",
"TTL": ttl, "TTL": ttl,
"ResourceRecords": [{"Value": ipaddress}], "ResourceRecords": [{"Value": ipaddress}],

View File

@ -96,7 +96,7 @@ class RovaSensor(Entity):
@property @property
def name(self): def name(self):
"""Return the name.""" """Return the name."""
return "{}_{}".format(self.platform_name, self.sensor_key) return f"{self.platform_name}_{self.sensor_key}"
@property @property
def icon(self): def icon(self):

View File

@ -79,7 +79,7 @@ class RTorrentSensor(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

@ -42,7 +42,7 @@ class SabnzbdSensor(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):
tv_name = discovery_info.get("name") tv_name = discovery_info.get("name")
model = discovery_info.get("model_name") model = discovery_info.get("model_name")
host = discovery_info.get("host") host = discovery_info.get("host")
name = "{} ({})".format(tv_name, model) name = f"{tv_name} ({model})"
port = DEFAULT_PORT port = DEFAULT_PORT
timeout = DEFAULT_TIMEOUT timeout = DEFAULT_TIMEOUT
mac = None mac = None

View File

@ -77,11 +77,11 @@ class SCSGate:
"""Handle a messages seen on the bus.""" """Handle a messages seen on the bus."""
from scsgate.messages import StateMessage, ScenarioTriggeredMessage from scsgate.messages import StateMessage, ScenarioTriggeredMessage
self._logger.debug("Received message {}".format(message)) self._logger.debug(f"Received message {message}")
if not isinstance(message, StateMessage) and not isinstance( if not isinstance(message, StateMessage) and not isinstance(
message, ScenarioTriggeredMessage message, ScenarioTriggeredMessage
): ):
msg = "Ignored message {} - not relevant type".format(message) msg = f"Ignored message {message} - not relevant type"
self._logger.debug(msg) self._logger.debug(msg)
return return
@ -97,7 +97,7 @@ class SCSGate:
try: try:
self._devices[message.entity].process_event(message) self._devices[message.entity].process_event(message)
except Exception as exception: # pylint: disable=broad-except except Exception as exception: # pylint: disable=broad-except
msg = "Exception while processing event: {}".format(exception) msg = f"Exception while processing event: {exception}"
self._logger.error(msg) self._logger.error(msg)
else: else:
self._logger.info( self._logger.info(

View File

@ -80,7 +80,7 @@ class Sense(Entity):
def __init__(self, data, name, sensor_type, is_production, update_call): def __init__(self, data, name, sensor_type, is_production, update_call):
"""Initialize the Sense sensor.""" """Initialize the Sense sensor."""
name_type = PRODUCTION_NAME if is_production else CONSUMPTION_NAME name_type = PRODUCTION_NAME if is_production else CONSUMPTION_NAME
self._name = "{} {}".format(name, name_type) self._name = f"{name} {name_type}"
self._data = data self._data = data
self._sensor_type = sensor_type self._sensor_type = sensor_type
self.update_sensor = update_call self.update_sensor = update_call

View File

@ -51,7 +51,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
if config.get(CONF_NAME) is not None: if config.get(CONF_NAME) is not None:
name = "{} PM{}".format(config.get(CONF_NAME), pmname) name = "{} PM{}".format(config.get(CONF_NAME), pmname)
else: else:
name = "PM{}".format(pmname) name = f"PM{pmname}"
dev.append(ParticulateMatterSensor(coll, name, pmname)) dev.append(ParticulateMatterSensor(coll, name, pmname))
add_entities(dev) add_entities(dev)

View File

@ -120,7 +120,7 @@ class SeventeenTrackSummarySensor(Entity):
@property @property
def name(self): def name(self):
"""Return the name.""" """Return the name."""
return "Seventeentrack Packages {0}".format(self._status) return f"Seventeentrack Packages {self._status}"
@property @property
def state(self): def state(self):
@ -203,7 +203,7 @@ class SeventeenTrackPackageSensor(Entity):
name = self._friendly_name name = self._friendly_name
if not name: if not name:
name = self._tracking_number name = self._tracking_number
return "Seventeentrack Package: {0}".format(name) return f"Seventeentrack Package: {name}"
@property @property
def state(self): def state(self):

View File

@ -69,10 +69,7 @@ def setup(hass, config):
if state.attributes: if state.attributes:
for attribute, data in state.attributes.items(): for attribute, data in state.attributes.items():
mqttc.publish( mqttc.publish(
"/{}/{}".format(topic, attribute), f"/{topic}/{attribute}", str(data), qos=0, retain=False
str(data),
qos=0,
retain=False,
) )
except RuntimeError: except RuntimeError:
pass pass

View File

@ -196,7 +196,7 @@ class AddItemIntent(intent.IntentHandler):
intent_obj.hass.data[DOMAIN].async_add(item) intent_obj.hass.data[DOMAIN].async_add(item)
response = intent_obj.create_response() response = intent_obj.create_response()
response.async_set_speech("I've added {} to your shopping list".format(item)) response.async_set_speech(f"I've added {item} to your shopping list")
intent_obj.hass.bus.async_fire(EVENT) intent_obj.hass.bus.async_fire(EVENT)
return response return response

View File

@ -90,7 +90,7 @@ class SigfoxAPI:
"""Get the device_id of each device registered.""" """Get the device_id of each device registered."""
devices = [] devices = []
for unique_type in device_types: for unique_type in device_types:
location_url = "devicetypes/{}/devices".format(unique_type) location_url = f"devicetypes/{unique_type}/devices"
url = urljoin(API_URL, location_url) url = urljoin(API_URL, location_url)
response = requests.get(url, auth=self._auth, timeout=10) response = requests.get(url, auth=self._auth, timeout=10)
devices_data = json.loads(response.text)["data"] devices_data = json.loads(response.text)["data"]
@ -117,12 +117,12 @@ class SigfoxDevice(Entity):
self._device_id = device_id self._device_id = device_id
self._auth = auth self._auth = auth
self._message_data = {} self._message_data = {}
self._name = "{}_{}".format(name, device_id) self._name = f"{name}_{device_id}"
self._state = None self._state = None
def get_last_message(self): def get_last_message(self):
"""Return the last message from a device.""" """Return the last message from a device."""
device_url = "devices/{}/messages?limit=1".format(self._device_id) device_url = f"devices/{self._device_id}/messages?limit=1"
url = urljoin(API_URL, device_url) url = urljoin(API_URL, device_url)
response = requests.get(url, auth=self._auth, timeout=10) response = requests.get(url, auth=self._auth, timeout=10)
data = json.loads(response.text)["data"][0] data = json.loads(response.text)["data"][0]

View File

@ -34,7 +34,7 @@ class SkyHubDeviceScanner(DeviceScanner):
_LOGGER.info("Initialising Sky Hub") _LOGGER.info("Initialising Sky Hub")
self.host = config.get(CONF_HOST, "192.168.1.254") self.host = config.get(CONF_HOST, "192.168.1.254")
self.last_results = {} self.last_results = {}
self.url = "http://{}/".format(self.host) self.url = f"http://{self.host}/"
# Test the router is accessible # Test the router is accessible
data = _get_skyhub_data(self.url) data = _get_skyhub_data(self.url)

View File

@ -57,7 +57,7 @@ class SkybellCamera(SkybellDevice, Camera):
SkybellDevice.__init__(self, device) SkybellDevice.__init__(self, device)
Camera.__init__(self) Camera.__init__(self)
if name is not None: if name is not None:
self._name = "{} {}".format(self._device.name, name) self._name = f"{self._device.name} {name}"
else: else:
self._name = self._device.name self._name = self._device.name
self._url = None self._url = None

View File

@ -50,7 +50,7 @@ def _check_sensor_schema(conf):
sensor, sensor,
) )
elif sensor not in valid: elif sensor not in valid:
raise vol.Invalid("{} does not exist".format(sensor)) raise vol.Invalid(f"{sensor} does not exist")
return conf return conf
@ -217,7 +217,7 @@ class SMAsensor(Entity):
update = False update = False
for sens in self._sub_sensors: # Can be remove from 0.99 for sens in self._sub_sensors: # Can be remove from 0.99
newval = "{} {}".format(sens.value, sens.unit) newval = f"{sens.value} {sens.unit}"
if self._attr[sens.name] != newval: if self._attr[sens.name] != newval:
update = True update = True
self._attr[sens.name] = newval self._attr[sens.name] = newval
@ -231,4 +231,4 @@ class SMAsensor(Entity):
@property @property
def unique_id(self): def unique_id(self):
"""Return a unique identifier for this sensor.""" """Return a unique identifier for this sensor."""
return "sma-{}-{}".format(self._sensor.key, self._sensor.name) return f"sma-{self._sensor.key}-{self._sensor.name}"

View File

@ -139,7 +139,7 @@ class SmappeeSensor(Entity):
else: else:
location_name = "Local" location_name = "Local"
return "{} {} {}".format(SENSOR_PREFIX, location_name, self._name) return f"{SENSOR_PREFIX} {location_name} {self._name}"
@property @property
def icon(self): def icon(self):

View File

@ -66,12 +66,12 @@ class SmartThingsBinarySensor(SmartThingsEntity, BinarySensorDevice):
@property @property
def name(self) -> str: def name(self) -> str:
"""Return the name of the binary sensor.""" """Return the name of the binary sensor."""
return "{} {}".format(self._device.label, self._attribute) return f"{self._device.label} {self._attribute}"
@property @property
def unique_id(self) -> str: def unique_id(self) -> str:
"""Return a unique ID.""" """Return a unique ID."""
return "{}.{}".format(self._device.device_id, self._attribute) return f"{self._device.device_id}.{self._attribute}"
@property @property
def is_on(self): def is_on(self):

View File

@ -283,12 +283,12 @@ class SmartThingsSensor(SmartThingsEntity):
@property @property
def name(self) -> str: def name(self) -> str:
"""Return the name of the binary sensor.""" """Return the name of the binary sensor."""
return "{} {}".format(self._device.label, self._name) return f"{self._device.label} {self._name}"
@property @property
def unique_id(self) -> str: def unique_id(self) -> str:
"""Return a unique ID.""" """Return a unique ID."""
return "{}.{}".format(self._device.device_id, self._attribute) return f"{self._device.device_id}.{self._attribute}"
@property @property
def state(self): def state(self):

View File

@ -112,7 +112,7 @@ def _get_app_template(hass: HomeAssistantType):
cloudhook_url = hass.data[DOMAIN][CONF_CLOUDHOOK_URL] cloudhook_url = hass.data[DOMAIN][CONF_CLOUDHOOK_URL]
if cloudhook_url is not None: if cloudhook_url is not None:
endpoint = "via Nabu Casa" endpoint = "via Nabu Casa"
description = "{} {}".format(hass.config.location_name, endpoint) description = f"{hass.config.location_name} {endpoint}"
return { return {
"app_name": APP_NAME_PREFIX + str(uuid4()), "app_name": APP_NAME_PREFIX + str(uuid4()),

View File

@ -69,9 +69,7 @@ class BoostSensor(SmartyBinarySensor):
def __init__(self, name, smarty): def __init__(self, name, smarty):
"""Alarm Sensor Init.""" """Alarm Sensor Init."""
super().__init__( super().__init__(name=f"{name} Boost State", device_class=None, smarty=smarty)
name="{} Boost State".format(name), device_class=None, smarty=smarty
)
def update(self) -> None: def update(self) -> None:
"""Update state.""" """Update state."""
@ -84,9 +82,7 @@ class AlarmSensor(SmartyBinarySensor):
def __init__(self, name, smarty): def __init__(self, name, smarty):
"""Alarm Sensor Init.""" """Alarm Sensor Init."""
super().__init__( super().__init__(name=f"{name} Alarm", device_class="problem", smarty=smarty)
name="{} Alarm".format(name), device_class="problem", smarty=smarty
)
def update(self) -> None: def update(self) -> None:
"""Update state.""" """Update state."""
@ -99,9 +95,7 @@ class WarningSensor(SmartyBinarySensor):
def __init__(self, name, smarty): def __init__(self, name, smarty):
"""Warning Sensor Init.""" """Warning Sensor Init."""
super().__init__( super().__init__(name=f"{name} Warning", device_class="problem", smarty=smarty)
name="{} Warning".format(name), device_class="problem", smarty=smarty
)
def update(self) -> None: def update(self) -> None:
"""Update state.""" """Update state."""

View File

@ -88,7 +88,7 @@ class SupplyAirTemperatureSensor(SmartySensor):
def __init__(self, name, smarty): def __init__(self, name, smarty):
"""Supply Air Temperature Init.""" """Supply Air Temperature Init."""
super().__init__( super().__init__(
name="{} Supply Air Temperature".format(name), name=f"{name} Supply Air Temperature",
device_class=DEVICE_CLASS_TEMPERATURE, device_class=DEVICE_CLASS_TEMPERATURE,
unit_of_measurement=TEMP_CELSIUS, unit_of_measurement=TEMP_CELSIUS,
smarty=smarty, smarty=smarty,
@ -106,7 +106,7 @@ class ExtractAirTemperatureSensor(SmartySensor):
def __init__(self, name, smarty): def __init__(self, name, smarty):
"""Supply Air Temperature Init.""" """Supply Air Temperature Init."""
super().__init__( super().__init__(
name="{} Extract Air Temperature".format(name), name=f"{name} Extract Air Temperature",
device_class=DEVICE_CLASS_TEMPERATURE, device_class=DEVICE_CLASS_TEMPERATURE,
unit_of_measurement=TEMP_CELSIUS, unit_of_measurement=TEMP_CELSIUS,
smarty=smarty, smarty=smarty,
@ -124,7 +124,7 @@ class OutdoorAirTemperatureSensor(SmartySensor):
def __init__(self, name, smarty): def __init__(self, name, smarty):
"""Outdoor Air Temperature Init.""" """Outdoor Air Temperature Init."""
super().__init__( super().__init__(
name="{} Outdoor Air Temperature".format(name), name=f"{name} Outdoor Air Temperature",
device_class=DEVICE_CLASS_TEMPERATURE, device_class=DEVICE_CLASS_TEMPERATURE,
unit_of_measurement=TEMP_CELSIUS, unit_of_measurement=TEMP_CELSIUS,
smarty=smarty, smarty=smarty,
@ -142,7 +142,7 @@ class SupplyFanSpeedSensor(SmartySensor):
def __init__(self, name, smarty): def __init__(self, name, smarty):
"""Supply Fan Speed RPM Init.""" """Supply Fan Speed RPM Init."""
super().__init__( super().__init__(
name="{} Supply Fan Speed".format(name), name=f"{name} Supply Fan Speed",
device_class=None, device_class=None,
unit_of_measurement=None, unit_of_measurement=None,
smarty=smarty, smarty=smarty,
@ -160,7 +160,7 @@ class ExtractFanSpeedSensor(SmartySensor):
def __init__(self, name, smarty): def __init__(self, name, smarty):
"""Extract Fan Speed RPM Init.""" """Extract Fan Speed RPM Init."""
super().__init__( super().__init__(
name="{} Extract Fan Speed".format(name), name=f"{name} Extract Fan Speed",
device_class=None, device_class=None,
unit_of_measurement=None, unit_of_measurement=None,
smarty=smarty, smarty=smarty,
@ -178,7 +178,7 @@ class FilterDaysLeftSensor(SmartySensor):
def __init__(self, name, smarty): def __init__(self, name, smarty):
"""Filter Days Left Init.""" """Filter Days Left Init."""
super().__init__( super().__init__(
name="{} Filter Days Left".format(name), name=f"{name} Filter Days Left",
device_class=DEVICE_CLASS_TIMESTAMP, device_class=DEVICE_CLASS_TIMESTAMP,
unit_of_measurement=None, unit_of_measurement=None,
smarty=smarty, smarty=smarty,

View File

@ -102,7 +102,7 @@ class SmhiWeather(WeatherEntity):
@property @property
def unique_id(self) -> str: def unique_id(self) -> str:
"""Return a unique id.""" """Return a unique id."""
return "{}, {}".format(self._latitude, self._longitude) return f"{self._latitude}, {self._longitude}"
@Throttle(MIN_TIME_BETWEEN_UPDATES) @Throttle(MIN_TIME_BETWEEN_UPDATES)
async def async_update(self) -> None: async def async_update(self) -> None:

View File

@ -182,7 +182,7 @@ class MailNotificationService(BaseNotificationService):
msg["Subject"] = subject msg["Subject"] = subject
msg["To"] = ",".join(self.recipients) msg["To"] = ",".join(self.recipients)
if self._sender_name: if self._sender_name:
msg["From"] = "{} <{}>".format(self._sender_name, self._sender) msg["From"] = f"{self._sender_name} <{self._sender}>"
else: else:
msg["From"] = self._sender msg["From"] = self._sender
msg["X-Mailer"] = "HomeAssistant" msg["X-Mailer"] = "HomeAssistant"
@ -225,18 +225,18 @@ def _build_multipart_msg(message, images):
msg.attach(msg_alt) msg.attach(msg_alt)
body_txt = MIMEText(message) body_txt = MIMEText(message)
msg_alt.attach(body_txt) msg_alt.attach(body_txt)
body_text = ["<p>{}</p><br>".format(message)] body_text = [f"<p>{message}</p><br>"]
for atch_num, atch_name in enumerate(images): for atch_num, atch_name in enumerate(images):
cid = "image{}".format(atch_num) cid = f"image{atch_num}"
body_text.append('<img src="cid:{}"><br>'.format(cid)) body_text.append(f'<img src="cid:{cid}"><br>')
try: try:
with open(atch_name, "rb") as attachment_file: with open(atch_name, "rb") as attachment_file:
file_bytes = attachment_file.read() file_bytes = attachment_file.read()
try: try:
attachment = MIMEImage(file_bytes) attachment = MIMEImage(file_bytes)
msg.attach(attachment) msg.attach(attachment)
attachment.add_header("Content-ID", "<{}>".format(cid)) attachment.add_header("Content-ID", f"<{cid}>")
except TypeError: except TypeError:
_LOGGER.warning( _LOGGER.warning(
"Attachment %s has an unknown MIME type. " "Attachment %s has an unknown MIME type. "
@ -271,7 +271,7 @@ def _build_html_msg(text, html, images):
with open(atch_name, "rb") as attachment_file: with open(atch_name, "rb") as attachment_file:
attachment = MIMEImage(attachment_file.read(), filename=name) attachment = MIMEImage(attachment_file.read(), filename=name)
msg.attach(attachment) msg.attach(attachment)
attachment.add_header("Content-ID", "<{}>".format(name)) attachment.add_header("Content-ID", f"<{name}>")
except FileNotFoundError: except FileNotFoundError:
_LOGGER.warning( _LOGGER.warning(
"Attachment %s [#%s] not found. Skipping", atch_name, atch_num "Attachment %s [#%s] not found. Skipping", atch_name, atch_num

View File

@ -98,7 +98,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
return return
# Note: Host part is needed, when using multiple snapservers # Note: Host part is needed, when using multiple snapservers
hpid = "{}:{}".format(host, port) hpid = f"{host}:{port}"
groups = [SnapcastGroupDevice(group, hpid) for group in server.groups] groups = [SnapcastGroupDevice(group, hpid) for group in server.groups]
clients = [SnapcastClientDevice(client, hpid) for client in server.clients] clients = [SnapcastClientDevice(client, hpid) for client in server.clients]
@ -114,7 +114,7 @@ class SnapcastGroupDevice(MediaPlayerDevice):
"""Initialize the Snapcast group device.""" """Initialize the Snapcast group device."""
group.set_callback(self.schedule_update_ha_state) group.set_callback(self.schedule_update_ha_state)
self._group = group self._group = group
self._uid = "{}{}_{}".format(GROUP_PREFIX, uid_part, self._group.identifier) self._uid = f"{GROUP_PREFIX}{uid_part}_{self._group.identifier}"
@property @property
def state(self): def state(self):
@ -133,7 +133,7 @@ class SnapcastGroupDevice(MediaPlayerDevice):
@property @property
def name(self): def name(self):
"""Return the name of the device.""" """Return the name of the device."""
return "{}{}".format(GROUP_PREFIX, self._group.identifier) return f"{GROUP_PREFIX}{self._group.identifier}"
@property @property
def source(self): def source(self):
@ -163,7 +163,7 @@ class SnapcastGroupDevice(MediaPlayerDevice):
@property @property
def device_state_attributes(self): def device_state_attributes(self):
"""Return the state attributes.""" """Return the state attributes."""
name = "{} {}".format(self._group.friendly_name, GROUP_SUFFIX) name = f"{self._group.friendly_name} {GROUP_SUFFIX}"
return {"friendly_name": name} return {"friendly_name": name}
@property @property
@ -204,7 +204,7 @@ class SnapcastClientDevice(MediaPlayerDevice):
"""Initialize the Snapcast client device.""" """Initialize the Snapcast client device."""
client.set_callback(self.schedule_update_ha_state) client.set_callback(self.schedule_update_ha_state)
self._client = client self._client = client
self._uid = "{}{}_{}".format(CLIENT_PREFIX, uid_part, self._client.identifier) self._uid = f"{CLIENT_PREFIX}{uid_part}_{self._client.identifier}"
@property @property
def unique_id(self): def unique_id(self):
@ -223,7 +223,7 @@ class SnapcastClientDevice(MediaPlayerDevice):
@property @property
def name(self): def name(self):
"""Return the name of the device.""" """Return the name of the device."""
return "{}{}".format(CLIENT_PREFIX, self._client.identifier) return f"{CLIENT_PREFIX}{self._client.identifier}"
@property @property
def source(self): def source(self):
@ -260,7 +260,7 @@ class SnapcastClientDevice(MediaPlayerDevice):
@property @property
def device_state_attributes(self): def device_state_attributes(self):
"""Return the state attributes.""" """Return the state attributes."""
name = "{} {}".format(self._client.friendly_name, CLIENT_SUFFIX) name = f"{self._client.friendly_name} {CLIENT_SUFFIX}"
return {"friendly_name": name} return {"friendly_name": name}
@property @property

View File

@ -67,7 +67,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
platform_name = config[CONF_NAME] platform_name = config[CONF_NAME]
# Create new SolarEdge object to retrieve data # Create new SolarEdge object to retrieve data
api = SolarEdge("http://{}/".format(ip_address)) api = SolarEdge(f"http://{ip_address}/")
# Check if api can be reached and site is active # Check if api can be reached and site is active
try: try:

View File

@ -35,7 +35,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
idx, unit = solax.INVERTER_SENSORS[sensor] idx, unit = solax.INVERTER_SENSORS[sensor]
if unit == "C": if unit == "C":
unit = TEMP_CELSIUS unit = TEMP_CELSIUS
uid = "{}-{}".format(serial, idx) uid = f"{serial}-{idx}"
devices.append(Inverter(uid, serial, sensor, unit)) devices.append(Inverter(uid, serial, sensor, unit))
endpoint.sensors = devices endpoint.sensors = devices
async_add_entities(devices) async_add_entities(devices)
@ -97,7 +97,7 @@ class Inverter(Entity):
@property @property
def name(self): def name(self):
"""Name of this inverter attribute.""" """Name of this inverter attribute."""
return "Solax {} {}".format(self.serial, self.key) return f"Solax {self.serial} {self.key}"
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):

View File

@ -73,7 +73,7 @@ class SomfyFlowHandler(config_entries.ConfigFlow):
client_id = self.hass.data[DOMAIN][CLIENT_ID] client_id = self.hass.data[DOMAIN][CLIENT_ID]
client_secret = self.hass.data[DOMAIN][CLIENT_SECRET] client_secret = self.hass.data[DOMAIN][CLIENT_SECRET]
redirect_uri = "{}{}".format(self.hass.config.api.base_url, AUTH_CALLBACK_PATH) redirect_uri = f"{self.hass.config.api.base_url}{AUTH_CALLBACK_PATH}"
api = SomfyApi(client_id, client_secret, redirect_uri) api = SomfyApi(client_id, client_secret, redirect_uri)
self.hass.http.register_view(SomfyAuthCallbackView()) self.hass.http.register_view(SomfyAuthCallbackView())
@ -95,7 +95,7 @@ class SomfyFlowHandler(config_entries.ConfigFlow):
code = self.code code = self.code
from pymfy.api.somfy_api import SomfyApi from pymfy.api.somfy_api import SomfyApi
redirect_uri = "{}{}".format(self.hass.config.api.base_url, AUTH_CALLBACK_PATH) redirect_uri = f"{self.hass.config.api.base_url}{AUTH_CALLBACK_PATH}"
api = SomfyApi(client_id, client_secret, redirect_uri) api = SomfyApi(client_id, client_secret, redirect_uri)
token = await self.hass.async_add_executor_job(api.request_token, None, code) token = await self.hass.async_add_executor_job(api.request_token, None, code)
_LOGGER.info("Successfully authenticated Somfy") _LOGGER.info("Successfully authenticated Somfy")

View File

@ -606,7 +606,7 @@ class SonosEntity(MediaPlayerDevice):
# media_artist = "Station - Artist - Title" # media_artist = "Station - Artist - Title"
# detect this case and trim from the front of # detect this case and trim from the front of
# media_artist for cosmetics # media_artist for cosmetics
trim = "{title} - ".format(title=self._media_title) trim = f"{self._media_title} - "
chars = min(len(self._media_artist), len(trim)) chars = min(len(self._media_artist), len(trim))
if self._media_artist[:chars].upper() == trim[:chars].upper(): if self._media_artist[:chars].upper() == trim[:chars].upper():

View File

@ -1,7 +1,7 @@
"""Consts used by Speedtest.net.""" """Consts used by Speedtest.net."""
DOMAIN = "speedtestdotnet" DOMAIN = "speedtestdotnet"
DATA_UPDATED = "{}_data_updated".format(DOMAIN) DATA_UPDATED = f"{DOMAIN}_data_updated"
SENSOR_TYPES = { SENSOR_TYPES = {
"ping": ["Ping", "ms"], "ping": ["Ping", "ms"],

View File

@ -29,7 +29,7 @@ CONF_DAYS = "days"
DEFAULT_DAYS = 1 DEFAULT_DAYS = 1
NAME = "spotcrime" NAME = "spotcrime"
EVENT_INCIDENT = "{}_incident".format(NAME) EVENT_INCIDENT = f"{NAME}_incident"
SCAN_INTERVAL = timedelta(minutes=30) SCAN_INTERVAL = timedelta(minutes=30)

View File

@ -99,7 +99,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Spotify platform.""" """Set up the Spotify platform."""
import spotipy.oauth2 import spotipy.oauth2
callback_url = "{}{}".format(hass.config.api.base_url, AUTH_CALLBACK_PATH) callback_url = f"{hass.config.api.base_url}{AUTH_CALLBACK_PATH}"
cache = config.get(CONF_CACHE_PATH, hass.config.path(DEFAULT_CACHE_PATH)) cache = config.get(CONF_CACHE_PATH, hass.config.path(DEFAULT_CACHE_PATH))
oauth = spotipy.oauth2.SpotifyOAuth( oauth = spotipy.oauth2.SpotifyOAuth(
config.get(CONF_CLIENT_ID), config.get(CONF_CLIENT_ID),

View File

@ -208,7 +208,7 @@ class LogitechMediaServer:
if self._username is None if self._username is None
else aiohttp.BasicAuth(self._username, self._password) else aiohttp.BasicAuth(self._username, self._password)
) )
url = "http://{}:{}/jsonrpc.js".format(self.host, self.port) url = f"http://{self.host}:{self.port}/jsonrpc.js"
data = json.dumps( data = json.dumps(
{"id": "1", "method": "slim.request", "params": [player, command]} {"id": "1", "method": "slim.request", "params": [player, command]}
) )
@ -288,9 +288,7 @@ class SqueezeBoxDevice(MediaPlayerDevice):
async def async_update(self): async def async_update(self):
"""Retrieve the current state of the player.""" """Retrieve the current state of the player."""
tags = "adKl" tags = "adKl"
response = await self.async_query( response = await self.async_query("status", "-", "1", f"tags:{tags}")
"status", "-", "1", "tags:{tags}".format(tags=tags)
)
if response is False: if response is False:
return return

View File

@ -87,7 +87,7 @@ class SrpEnergy(Entity):
if self._state is None: if self._state is None:
return None return None
return "{0:.2f}".format(self._state) return f"{self._state:.2f}"
@property @property
def name(self): def name(self):

View File

@ -86,7 +86,7 @@ class StartcaSensor(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

@ -80,7 +80,7 @@ class SteamSensor(Entity):
@property @property
def entity_id(self): def entity_id(self):
"""Return the entity ID.""" """Return the entity ID."""
return "sensor.steam_{}".format(self._account) return f"sensor.steam_{self._account}"
@property @property
def state(self): def state(self):

View File

@ -139,7 +139,7 @@ class StiebelEltron(ClimateDevice):
@property @property
def current_humidity(self): def current_humidity(self):
"""Return the current humidity.""" """Return the current humidity."""
return float("{0:.1f}".format(self._current_humidity)) return float(f"{self._current_humidity:.1f}")
@property @property
def hvac_modes(self): def hvac_modes(self):

View File

@ -217,9 +217,7 @@ async def async_handle_record_service(hass, call):
# Check for file access # Check for file access
if not hass.config.is_allowed_path(video_path): if not hass.config.is_allowed_path(video_path):
raise HomeAssistantError( raise HomeAssistantError(f"Can't write {video_path}, no access to path!")
"Can't write {}, no access to path!".format(video_path)
)
# Check for active stream # Check for active stream
streams = hass.data[DOMAIN][ATTR_STREAMS] streams = hass.data[DOMAIN][ATTR_STREAMS]
@ -231,9 +229,7 @@ async def async_handle_record_service(hass, call):
# Add recorder # Add recorder
recorder = stream.outputs.get("recorder") recorder = stream.outputs.get("recorder")
if recorder: if recorder:
raise HomeAssistantError( raise HomeAssistantError(f"Stream already recording to {recorder.video_path}!")
"Stream already recording to {}!".format(recorder.video_path)
)
recorder = stream.add_provider("recorder") recorder = stream.add_provider("recorder")
recorder.video_path = video_path recorder.video_path = video_path

View File

@ -64,10 +64,7 @@ class M3U8Renderer:
@staticmethod @staticmethod
def render_preamble(track): def render_preamble(track):
"""Render preamble.""" """Render preamble."""
return [ return ["#EXT-X-VERSION:3", f"#EXT-X-TARGETDURATION:{track.target_duration}"]
"#EXT-X-VERSION:3",
"#EXT-X-TARGETDURATION:{}".format(track.target_duration),
]
@staticmethod @staticmethod
def render_playlist(track, start_time): def render_playlist(track, start_time):
@ -84,7 +81,7 @@ class M3U8Renderer:
playlist.extend( playlist.extend(
[ [
"#EXTINF:{:.04f},".format(float(segment.duration)), "#EXTINF:{:.04f},".format(float(segment.duration)),
"./segment/{}.ts".format(segment.sequence), f"./segment/{segment.sequence}.ts",
] ]
) )

View File

@ -58,7 +58,7 @@ class StreamlabsAwayMode(BinarySensorDevice):
@property @property
def name(self): def name(self):
"""Return the name for away mode.""" """Return the name for away mode."""
return "{} {}".format(self._location_name, NAME_AWAY_MODE) return f"{self._location_name} {NAME_AWAY_MODE}"
@property @property
def is_on(self): def is_on(self):

View File

@ -79,7 +79,7 @@ class StreamLabsDailyUsage(Entity):
@property @property
def name(self): def name(self):
"""Return the name for daily usage.""" """Return the name for daily usage."""
return "{} {}".format(self._location_name, NAME_DAILY_USAGE) return f"{self._location_name} {NAME_DAILY_USAGE}"
@property @property
def icon(self): def icon(self):
@ -107,7 +107,7 @@ class StreamLabsMonthlyUsage(StreamLabsDailyUsage):
@property @property
def name(self): def name(self):
"""Return the name for monthly usage.""" """Return the name for monthly usage."""
return "{} {}".format(self._location_name, NAME_MONTHLY_USAGE) return f"{self._location_name} {NAME_MONTHLY_USAGE}"
@property @property
def state(self): def state(self):
@ -121,7 +121,7 @@ class StreamLabsYearlyUsage(StreamLabsDailyUsage):
@property @property
def name(self): def name(self):
"""Return the name for yearly usage.""" """Return the name for yearly usage."""
return "{} {}".format(self._location_name, NAME_YEARLY_USAGE) return f"{self._location_name} {NAME_YEARLY_USAGE}"
@property @property
def state(self): def state(self):

View File

@ -101,7 +101,7 @@ class SwissHydrologicalDataSensor(Entity):
@property @property
def unique_id(self) -> str: def unique_id(self) -> str:
"""Return a unique, friendly identifier for this entity.""" """Return a unique, friendly identifier for this entity."""
return "{0}_{1}".format(self._station, self._condition) return f"{self._station}_{self._condition}"
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):

View File

@ -110,7 +110,7 @@ class SwissPublicTransportSensor(Entity):
ATTR_DEPARTURE_TIME2: self._opendata.connections[2]["departure"], ATTR_DEPARTURE_TIME2: self._opendata.connections[2]["departure"],
ATTR_START: self._opendata.from_name, ATTR_START: self._opendata.from_name,
ATTR_TARGET: self._opendata.to_name, ATTR_TARGET: self._opendata.to_name,
ATTR_REMAINING_TIME: "{}".format(self._remaining_time), ATTR_REMAINING_TIME: f"{self._remaining_time}",
ATTR_ATTRIBUTION: ATTRIBUTION, ATTR_ATTRIBUTION: ATTRIBUTION,
} }
return attr return attr

View File

@ -74,7 +74,7 @@ class SwisscomDeviceScanner(DeviceScanner):
def get_swisscom_data(self): def get_swisscom_data(self):
"""Retrieve data from Swisscom and return parsed result.""" """Retrieve data from Swisscom and return parsed result."""
url = "http://{}/ws".format(self.host) url = f"http://{self.host}/ws"
headers = {CONTENT_TYPE: "application/x-sah-ws-4-call+json"} headers = {CONTENT_TYPE: "application/x-sah-ws-4-call+json"}
data = """ data = """
{"service":"Devices", "method":"get", {"service":"Devices", "method":"get",

View File

@ -65,7 +65,7 @@ class SwitcherControl(SwitchDevice):
@property @property
def unique_id(self) -> str: def unique_id(self) -> str:
"""Return a unique ID.""" """Return a unique ID."""
return "{}-{}".format(self._device_data.device_id, self._device_data.mac_addr) return f"{self._device_data.device_id}-{self._device_data.mac_addr}"
@property @property
def is_on(self) -> bool: def is_on(self) -> bool:

View File

@ -18,12 +18,10 @@ TONER_COLORS = COLORS
TRAYS = range(1, 6) TRAYS = range(1, 6)
OUTPUT_TRAYS = range(0, 6) OUTPUT_TRAYS = range(0, 6)
DEFAULT_MONITORED_CONDITIONS = [] DEFAULT_MONITORED_CONDITIONS = []
DEFAULT_MONITORED_CONDITIONS.extend(["toner_{}".format(key) for key in TONER_COLORS]) DEFAULT_MONITORED_CONDITIONS.extend([f"toner_{key}" for key in TONER_COLORS])
DEFAULT_MONITORED_CONDITIONS.extend(["drum_{}".format(key) for key in DRUM_COLORS]) DEFAULT_MONITORED_CONDITIONS.extend([f"drum_{key}" for key in DRUM_COLORS])
DEFAULT_MONITORED_CONDITIONS.extend(["tray_{}".format(key) for key in TRAYS]) DEFAULT_MONITORED_CONDITIONS.extend([f"tray_{key}" for key in TRAYS])
DEFAULT_MONITORED_CONDITIONS.extend( DEFAULT_MONITORED_CONDITIONS.extend([f"output_tray_{key}" for key in OUTPUT_TRAYS])
["output_tray_{}".format(key) for key in OUTPUT_TRAYS]
)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend( PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{ {
@ -81,16 +79,16 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
devices = [SyncThruMainSensor(printer, name)] devices = [SyncThruMainSensor(printer, name)]
for key in supp_toner: for key in supp_toner:
if "toner_{}".format(key) in monitored: if f"toner_{key}" in monitored:
devices.append(SyncThruTonerSensor(printer, name, key)) devices.append(SyncThruTonerSensor(printer, name, key))
for key in supp_drum: for key in supp_drum:
if "drum_{}".format(key) in monitored: if f"drum_{key}" in monitored:
devices.append(SyncThruDrumSensor(printer, name, key)) devices.append(SyncThruDrumSensor(printer, name, key))
for key in supp_tray: for key in supp_tray:
if "tray_{}".format(key) in monitored: if f"tray_{key}" in monitored:
devices.append(SyncThruInputTraySensor(printer, name, key)) devices.append(SyncThruInputTraySensor(printer, name, key))
for key in supp_output_tray: for key in supp_output_tray:
if "output_tray_{}".format(key) in monitored: if f"output_tray_{key}" in monitored:
devices.append(SyncThruOutputTraySensor(printer, name, key)) devices.append(SyncThruOutputTraySensor(printer, name, key))
async_add_entities(devices, True) async_add_entities(devices, True)
@ -173,10 +171,10 @@ class SyncThruTonerSensor(SyncThruSensor):
def __init__(self, syncthru, name, color): def __init__(self, syncthru, name, color):
"""Initialize the sensor.""" """Initialize the sensor."""
super().__init__(syncthru, name) super().__init__(syncthru, name)
self._name = "{} Toner {}".format(name, color) self._name = f"{name} Toner {color}"
self._color = color self._color = color
self._unit_of_measurement = "%" self._unit_of_measurement = "%"
self._id_suffix = "_toner_{}".format(color) self._id_suffix = f"_toner_{color}"
def update(self): def update(self):
"""Get the latest data from SyncThru and update the state.""" """Get the latest data from SyncThru and update the state."""
@ -193,10 +191,10 @@ class SyncThruDrumSensor(SyncThruSensor):
def __init__(self, syncthru, name, color): def __init__(self, syncthru, name, color):
"""Initialize the sensor.""" """Initialize the sensor."""
super().__init__(syncthru, name) super().__init__(syncthru, name)
self._name = "{} Drum {}".format(name, color) self._name = f"{name} Drum {color}"
self._color = color self._color = color
self._unit_of_measurement = "%" self._unit_of_measurement = "%"
self._id_suffix = "_drum_{}".format(color) self._id_suffix = f"_drum_{color}"
def update(self): def update(self):
"""Get the latest data from SyncThru and update the state.""" """Get the latest data from SyncThru and update the state."""
@ -213,9 +211,9 @@ class SyncThruInputTraySensor(SyncThruSensor):
def __init__(self, syncthru, name, number): def __init__(self, syncthru, name, number):
"""Initialize the sensor.""" """Initialize the sensor."""
super().__init__(syncthru, name) super().__init__(syncthru, name)
self._name = "{} Tray {}".format(name, number) self._name = f"{name} Tray {number}"
self._number = number self._number = number
self._id_suffix = "_tray_{}".format(number) self._id_suffix = f"_tray_{number}"
def update(self): def update(self):
"""Get the latest data from SyncThru and update the state.""" """Get the latest data from SyncThru and update the state."""
@ -234,9 +232,9 @@ class SyncThruOutputTraySensor(SyncThruSensor):
def __init__(self, syncthru, name, number): def __init__(self, syncthru, name, number):
"""Initialize the sensor.""" """Initialize the sensor."""
super().__init__(syncthru, name) super().__init__(syncthru, name)
self._name = "{} Output Tray {}".format(name, number) self._name = f"{name} Output Tray {number}"
self._number = number self._number = number
self._id_suffix = "_output_tray_{}".format(number) self._id_suffix = f"_output_tray_{number}"
def update(self): def update(self):
"""Get the latest data from SyncThru and update the state.""" """Get the latest data from SyncThru and update the state."""

View File

@ -184,7 +184,7 @@ class SynoNasSensor(Entity):
def name(self): def name(self):
"""Return the name of the sensor, if any.""" """Return the name of the sensor, if any."""
if self.monitor_device is not None: if self.monitor_device is not None:
return "{} ({})".format(self.var_name, self.monitor_device) return f"{self.var_name} ({self.monitor_device})"
return self.var_name return self.var_name
@property @property

View File

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