Use literal string interpolation in integrations N-Q (f-strings) (#26391)

This commit is contained in:
Franck Nijhof 2019-09-03 20:35:00 +02:00 committed by Paulus Schoutsen
parent 330ae0d885
commit 1c5e0123c9
62 changed files with 103 additions and 113 deletions

View File

@ -127,7 +127,7 @@ class NeatoConnectedVacuum(StateVacuumDevice):
"""Initialize the Neato Connected Vacuum."""
self.robot = robot
self.neato = hass.data[NEATO_LOGIN]
self._name = "{}".format(self.robot.name)
self._name = f"{self.robot.name}"
self._status_state = None
self._clean_state = None
self._state = None

View File

@ -59,7 +59,7 @@ class NelloLock(LockDevice):
location_id = self._nello_lock.location_id
short_id = self._nello_lock.short_id
address = self._nello_lock.address
self._name = "Nello {}".format(short_id)
self._name = f"Nello {short_id}"
self._device_attrs = {ATTR_ADDRESS: address, ATTR_LOCATION_ID: location_id}
# Process recent activity
activity = self._nello_lock.activity

View File

@ -405,7 +405,7 @@ class NestSensorDevice(Entity):
@property
def unique_id(self):
"""Return unique id based on device serial and variable."""
return "{}-{}".format(self.device.serial, self.variable)
return f"{self.device.serial}-{self.variable}"
@property
def device_info(self):

View File

@ -143,12 +143,12 @@ class NestActivityZoneSensor(NestBinarySensor):
"""Initialize the sensor."""
super(NestActivityZoneSensor, self).__init__(structure, device, "")
self.zone = zone
self._name = "{} {} activity".format(self._name, self.zone.name)
self._name = f"{self._name} {self.zone.name} activity"
@property
def unique_id(self):
"""Return unique id based on camera serial and zone id."""
return "{}-{}".format(self.device.serial, self.zone.zone_id)
return f"{self.device.serial}-{self.zone.zone_id}"
@property
def device_class(self):

View File

@ -45,5 +45,5 @@ async def resolve_auth_code(hass, client_id, client_secret, code):
if err.response.status_code == 401:
raise config_flow.CodeInvalid()
raise config_flow.NestAuthError(
"Unknown error: {} ({})".format(err, err.response.status_code)
f"Unknown error: {err} ({err.response.status_code})"
)

View File

@ -152,7 +152,7 @@ class NetatmoBinarySensor(BinarySensorDevice):
self._home = home
self._timeout = timeout
if home:
self._name = "{} / {}".format(home, camera_name)
self._name = f"{home} / {camera_name}"
else:
self._name = camera_name
if module_name:

View File

@ -88,11 +88,11 @@ class NetatmoCamera(Camera):
try:
if self._localurl:
response = requests.get(
"{0}/live/snapshot_720.jpg".format(self._localurl), timeout=10
f"{self._localurl}/live/snapshot_720.jpg", timeout=10
)
elif self._vpnurl:
response = requests.get(
"{0}/live/snapshot_720.jpg".format(self._vpnurl),
f"{self._vpnurl}/live/snapshot_720.jpg",
timeout=10,
verify=self._verify_ssl,
)

View File

@ -154,7 +154,7 @@ class NetatmoThermostat(ClimateDevice):
self._state = None
self._room_id = room_id
self._room_name = self._data.homedata.rooms[self._data.home_id][room_id]["name"]
self._name = "netatmo_{}".format(self._room_name)
self._name = f"netatmo_{self._room_name}"
self._current_temperature = None
self._target_temperature = None
self._preset = None

View File

@ -112,7 +112,7 @@ class NetdataSensor(Entity):
@property
def name(self):
"""Return the name of the sensor."""
return "{} {}".format(self._name, self._sensor_name)
return f"{self._name} {self._sensor_name}"
@property
def unit_of_measurement(self):

View File

@ -350,7 +350,7 @@ class LTEEntity(Entity):
@_unique_id.default
def _init_unique_id(self):
"""Register unique_id while we know data is valid."""
return "{}_{}".format(self.sensor_type, self.modem_data.data.serial_number)
return f"{self.sensor_type}_{self.modem_data.data.serial_number}"
async def async_added_to_hass(self):
"""Register callback."""
@ -380,4 +380,4 @@ class LTEEntity(Entity):
@property
def name(self):
"""Return the name of the sensor."""
return "Netgear LTE {}".format(self.sensor_type)
return f"Netgear LTE {self.sensor_type}"

View File

@ -62,9 +62,7 @@ def validate_value(value_name, value, value_list):
"Invalid %s tag `%s`. Please use one of the following: %s",
value_name,
value,
", ".join(
"{}: {}".format(title, tag) for tag, title in valid_values.items()
),
", ".join(f"{title}: {tag}" for tag, title in valid_values.items()),
)
return False
@ -126,7 +124,7 @@ class NextBusDepartureSensor(Entity):
self.stop = stop
self._custom_name = name
# Maybe pull a more user friendly name from the API here
self._name = "{} {}".format(agency, route)
self._name = f"{agency} {route}"
self._client = client
# set up default state attributes

View File

@ -137,7 +137,7 @@ class NFAndroidTVNotificationService(BaseNotificationService):
is_allowed_path,
):
"""Initialize the service."""
self._target = "http://{}:7676".format(remoteip)
self._target = f"http://{remoteip}:7676"
self._default_duration = duration
self._default_fontsize = fontsize
self._default_position = position

View File

@ -46,7 +46,7 @@ class NikoHomeControlLight(Light):
"""Set up the Niko Home Control light platform."""
self._data = data
self._light = light
self._unique_id = "light-{}".format(light.id)
self._unique_id = f"light-{light.id}"
self._name = light.name
self._state = light.is_on
self._brightness = None

View File

@ -147,7 +147,7 @@ class NiluSensor(AirQualityEntity):
def __init__(self, api_data: NiluData, name: str, show_on_map: bool):
"""Initialize the sensor."""
self._api = api_data
self._name = "{} {}".format(name, api_data.data.name)
self._name = f"{name} {api_data.data.name}"
self._max_aqi = None
self._attrs = {}

View File

@ -124,7 +124,7 @@ class NMBSLiveBoard(Entity):
departure = get_time_until(self._attrs["time"])
attrs = {
"departure": "In {} minutes".format(departure),
"departure": f"In {departure} minutes",
"extra_train": int(self._attrs["isExtra"]) > 0,
"vehicle_id": self._attrs["vehicle"],
"monitored_station": self._station,
@ -132,7 +132,7 @@ class NMBSLiveBoard(Entity):
}
if delay > 0:
attrs["delay"] = "{} minutes".format(delay)
attrs["delay"] = f"{delay} minutes"
return attrs
@ -194,7 +194,7 @@ class NMBSSensor(Entity):
departure = get_time_until(self._attrs["departure"]["time"])
attrs = {
"departure": "In {} minutes".format(departure),
"departure": f"In {departure} minutes",
"destination": self._station_to,
"direction": self._attrs["departure"]["direction"]["name"],
"platform_arriving": self._attrs["arrival"]["platform"],
@ -218,7 +218,7 @@ class NMBSSensor(Entity):
) + get_delay_in_minutes(via["departure"]["delay"])
if delay > 0:
attrs["delay"] = "{} minutes".format(delay)
attrs["delay"] = f"{delay} minutes"
return attrs

View File

@ -34,7 +34,7 @@ NO_IP_ERRORS = {
}
UPDATE_URL = "https://dynupdate.noip.com/nic/update"
HA_USER_AGENT = "{} {}".format(SERVER_SOFTWARE, EMAIL)
HA_USER_AGENT = f"{SERVER_SOFTWARE} {EMAIL}"
CONFIG_SCHEMA = vol.Schema(
{
@ -58,7 +58,7 @@ async def async_setup(hass, config):
password = config[DOMAIN].get(CONF_PASSWORD)
timeout = config[DOMAIN].get(CONF_TIMEOUT)
auth_str = base64.b64encode("{}:{}".format(user, password).encode("utf-8"))
auth_str = base64.b64encode(f"{user}:{password}".encode("utf-8"))
session = hass.helpers.aiohttp_client.async_get_clientsession()

View File

@ -101,10 +101,10 @@ class NOAATidesAndCurrentsSensor(Entity):
api_time = self.data.index[0]
if self.data["hi_lo"][0] == "H":
tidetime = api_time.strftime("%-I:%M %p")
return "High tide at {}".format(tidetime)
return f"High tide at {tidetime}"
if self.data["hi_lo"][0] == "L":
tidetime = api_time.strftime("%-I:%M %p")
return "Low tide at {}".format(tidetime)
return f"Low tide at {tidetime}"
return None
def update(self):

View File

@ -124,7 +124,7 @@ async def async_setup(hass, config):
p_config.get(CONF_NAME) or discovery_info.get(CONF_NAME) or p_type
)
for name, target in notify_service.targets.items():
target_name = slugify("{}_{}".format(platform_name, name))
target_name = slugify(f"{platform_name}_{name}")
targets[target_name] = target
hass.services.async_register(
DOMAIN,
@ -145,7 +145,7 @@ async def async_setup(hass, config):
schema=NOTIFY_SERVICE_SCHEMA,
)
hass.config.components.add("{}.{}".format(DOMAIN, p_type))
hass.config.components.add(f"{DOMAIN}.{p_type}")
return True

View File

@ -141,7 +141,7 @@ class StationPriceData:
None,
)
self._station_name = name or "station {}".format(self.station_id)
self._station_name = name or f"station {self.station_id}"
return self._station_name

View File

@ -38,7 +38,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([NX584Alarm(hass, url, name)])

View File

@ -47,7 +47,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
zone_types = config.get(CONF_ZONE_TYPES)
try:
client = nx584_client.Client("http://{}:{}".format(host, port))
client = nx584_client.Client(f"http://{host}:{port}")
zones = client.list_zones()
except requests.exceptions.ConnectionError as ex:
_LOGGER.error("Unable to connect to NX584: %s", str(ex))

View File

@ -65,7 +65,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
password = config.get(CONF_PASSWORD)
monitored_types = config.get(CONF_MONITORED_VARIABLES)
url = "http{}://{}:{}/jsonrpc".format(ssl, host, port)
url = f"http{ssl}://{host}:{port}/jsonrpc"
try:
nzbgetapi = NZBGetAPI(api_url=url, username=username, password=password)

View File

@ -45,9 +45,9 @@ class OctoPrintBinarySensor(BinarySensorDevice):
"""Initialize a new OctoPrint sensor."""
self.sensor_name = sensor_name
if tool is None:
self._name = "{} {}".format(sensor_name, condition)
self._name = f"{sensor_name} {condition}"
else:
self._name = "{} {}".format(sensor_name, condition)
self._name = f"{sensor_name} {condition}"
self.sensor_type = sensor_type
self.api = api
self._state = False

View File

@ -89,7 +89,7 @@ class OctoPrintSensor(Entity):
"""Initialize a new OctoPrint sensor."""
self.sensor_name = sensor_name
if tool is None:
self._name = "{} {}".format(sensor_name, condition)
self._name = f"{sensor_name} {condition}"
else:
self._name = "{} {} {} {}".format(sensor_name, condition, tool, "temp")
self.sensor_type = sensor_type

View File

@ -122,7 +122,7 @@ class UserOnboardingView(_BaseOnboardingView):
for area in DEFAULT_AREAS:
area_registry.async_create(
translations["component.onboarding.area.{}".format(area)]
translations[f"component.onboarding.area.{area}"]
)
await self._async_mark_done(hass)

View File

@ -267,7 +267,7 @@ class ONVIFHassCamera(Camera):
uri_no_auth = stream_uri.Uri
uri_for_log = uri_no_auth.replace("rtsp://", "rtsp://<user>:<password>@", 1)
self._input = uri_no_auth.replace(
"rtsp://", "rtsp://{}:{}@".format(self._username, self._password), 1
"rtsp://", f"rtsp://{self._username}:{self._password}@", 1
)
_LOGGER.debug(

View File

@ -122,9 +122,7 @@ class OpenGarageCover(CoverDevice):
def update(self):
"""Get updated status from API."""
try:
status = requests.get(
"{}/jc".format(self.opengarage_url), timeout=10
).json()
status = requests.get(f"{self.opengarage_url}/jc", timeout=10).json()
except requests.exceptions.RequestException as ex:
_LOGGER.error(
"Unable to connect to OpenGarage device: %(reason)s", dict(reason=ex)
@ -157,8 +155,7 @@ class OpenGarageCover(CoverDevice):
result = -1
try:
result = requests.get(
"{}/cc?dkey={}&click=1".format(self.opengarage_url, self._device_key),
timeout=10,
f"{self.opengarage_url}/cc?dkey={self._device_key}&click=1", timeout=10
).json()["result"]
except requests.exceptions.RequestException as ex:
_LOGGER.error(

View File

@ -36,8 +36,8 @@ DOMAIN = "opensky"
DEFAULT_ALTITUDE = 0
EVENT_OPENSKY_ENTRY = "{}_entry".format(DOMAIN)
EVENT_OPENSKY_EXIT = "{}_exit".format(DOMAIN)
EVENT_OPENSKY_ENTRY = f"{DOMAIN}_entry"
EVENT_OPENSKY_EXIT = f"{DOMAIN}_exit"
SCAN_INTERVAL = timedelta(seconds=12) # opensky public limit is 10 seconds
OPENSKY_ATTRIBUTION = (

View File

@ -260,7 +260,7 @@ def register_services(hass):
gpio_id = call.data[ATTR_ID]
gpio_mode = call.data[ATTR_MODE]
mode = await gw_dev.gateway.set_gpio_mode(gpio_id, gpio_mode)
gpio_var = getattr(gw_vars, "OTGW_GPIO_{}".format(gpio_id))
gpio_var = getattr(gw_vars, f"OTGW_GPIO_{gpio_id}")
gw_dev.status.update({gpio_var: mode})
async_dispatcher_send(hass, gw_dev.update_signal, gw_dev.status)
@ -274,7 +274,7 @@ def register_services(hass):
led_id = call.data[ATTR_ID]
led_mode = call.data[ATTR_MODE]
mode = await gw_dev.gateway.set_led_mode(led_id, led_mode)
led_var = getattr(gw_vars, "OTGW_LED_{}".format(led_id))
led_var = getattr(gw_vars, f"OTGW_LED_{led_id}")
gw_dev.status.update({led_var: mode})
async_dispatcher_send(hass, gw_dev.update_signal, gw_dev.status)
@ -333,7 +333,7 @@ class OpenThermGatewayDevice:
self.name = config.get(CONF_NAME, gw_id)
self.climate_config = config[CONF_CLIMATE]
self.status = {}
self.update_signal = "{}_{}_update".format(DATA_OPENTHERM_GW, gw_id)
self.update_signal = f"{DATA_OPENTHERM_GW}_{gw_id}_update"
self.gateway = pyotgw.pyotgw()
async def connect_and_subscribe(self, device_path):

View File

@ -33,7 +33,7 @@ class OpenThermBinarySensor(BinarySensorDevice):
def __init__(self, gw_dev, var, device_class, friendly_name_format):
"""Initialize the binary sensor."""
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, "{}_{}".format(var, gw_dev.gw_id), hass=gw_dev.hass
ENTITY_ID_FORMAT, f"{var}_{gw_dev.gw_id}", hass=gw_dev.hass
)
self._gateway = gw_dev
self._var = var

View File

@ -34,7 +34,7 @@ class OpenThermSensor(Entity):
def __init__(self, gw_dev, var, device_class, unit, friendly_name_format):
"""Initialize the OpenTherm Gateway sensor."""
self.entity_id = async_generate_entity_id(
ENTITY_ID_FORMAT, "{}_{}".format(var, gw_dev.gw_id), hass=gw_dev.hass
ENTITY_ID_FORMAT, f"{var}_{gw_dev.gw_id}", hass=gw_dev.hass
)
self._gateway = gw_dev
self._var = var
@ -55,7 +55,7 @@ class OpenThermSensor(Entity):
"""Handle status updates from the component."""
value = status.get(self._var)
if isinstance(value, float):
value = "{:2.1f}".format(value)
value = f"{value:2.1f}"
self._value = value
self.async_schedule_update_ha_state()

View File

@ -36,7 +36,7 @@ DEFAULT_ATTRIBUTION = "Data provided by OpenUV"
NOTIFICATION_ID = "openuv_notification"
NOTIFICATION_TITLE = "OpenUV Component Setup"
TOPIC_UPDATE = "{0}_data_update".format(DOMAIN)
TOPIC_UPDATE = f"{DOMAIN}_data_update"
TYPE_CURRENT_OZONE_LEVEL = "current_ozone_level"
TYPE_CURRENT_UV_INDEX = "current_uv_index"

View File

@ -76,7 +76,7 @@ class OpenUvBinarySensor(OpenUvEntity, BinarySensorDevice):
@property
def unique_id(self) -> str:
"""Return a unique, HASS-friendly identifier for this entity."""
return "{0}_{1}_{2}".format(self._latitude, self._longitude, self._sensor_type)
return f"{self._latitude}_{self._longitude}_{self._sensor_type}"
async def async_added_to_hass(self):
"""Register callbacks."""

View File

@ -98,7 +98,7 @@ class OpenUvSensor(OpenUvEntity):
@property
def unique_id(self) -> str:
"""Return a unique, HASS-friendly identifier for this entity."""
return "{0}_{1}_{2}".format(self._latitude, self._longitude, self._sensor_type)
return f"{self._latitude}_{self._longitude}_{self._sensor_type}"
@property
def unit_of_measurement(self):

View File

@ -108,7 +108,7 @@ class OpenWeatherMapSensor(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

@ -58,7 +58,7 @@ def setup(hass, config):
device.update_properties()
if not name:
name = "{}'s Owlet".format(device.baby_name)
name = f"{device.baby_name}'s Owlet"
hass.data[DOMAIN] = OwletDevice(device, name, SENSOR_TYPES)

View File

@ -169,7 +169,7 @@ async def handle_webhook(hass, webhook_id, request):
if user:
topic_base = re.sub("/#$", "", context.mqtt_topic)
message["topic"] = "{}/{}/{}".format(topic_base, user, device)
message["topic"] = f"{topic_base}/{user}/{device}"
elif message["_type"] != "encrypted":
_LOGGER.warning(
@ -264,7 +264,7 @@ class OwnTracksContext:
# Mobile beacons should always be set to the location of the
# tracking device. I get the device state and make the necessary
# changes to kwargs.
device_tracker_state = hass.states.get("device_tracker.{}".format(dev_id))
device_tracker_state = hass.states.get(f"device_tracker.{dev_id}")
if device_tracker_state is not None:
acc = device_tracker_state.attributes.get("gps_accuracy")
@ -282,6 +282,6 @@ class OwnTracksContext:
# kwargs location is the beacon's configured lat/lon
kwargs.pop("battery", None)
for beacon in self.mobile_beacons_active[dev_id]:
kwargs["dev_id"] = "{}_{}".format(BEACON_DEV_ID, beacon)
kwargs["dev_id"] = f"{BEACON_DEV_ID}_{beacon}"
kwargs["host_name"] = beacon
self.async_see(**kwargs)

View File

@ -60,7 +60,7 @@ def _parse_see_args(message, subscribe_topic):
Async friendly.
"""
user, device = _parse_topic(message["topic"], subscribe_topic)
dev_id = slugify("{}_{}".format(user, device))
dev_id = slugify(f"{user}_{device}")
kwargs = {"dev_id": dev_id, "host_name": user, "attributes": {}}
if message["lat"] is not None and message["lon"] is not None:
kwargs["gps"] = (message["lat"], message["lon"])
@ -253,7 +253,7 @@ async def async_handle_transition_message(hass, context, message):
async def async_handle_waypoint(hass, name_base, waypoint):
"""Handle a waypoint."""
name = waypoint["desc"]
pretty_name = "{} - {}".format(name_base, name)
pretty_name = f"{name_base} - {name}"
lat = waypoint["lat"]
lon = waypoint["lon"]
rad = waypoint["rad"]

View File

@ -220,7 +220,7 @@ class PandoraMediaPlayer(MediaPlayerDevice):
return
_LOGGER.debug("Setting station %s, %d", source, station_index)
self._send_station_list_command()
self._pianobar.sendline("{}".format(station_index))
self._pianobar.sendline(f"{station_index}")
self._pianobar.expect("\r\n")
self._player_state = STATE_PLAYING

View File

@ -165,7 +165,7 @@ async def async_setup(hass, config):
panel_path = panel.get(CONF_WEBCOMPONENT_PATH)
if panel_path is None:
panel_path = hass.config.path(PANEL_DIR, "{}.html".format(name))
panel_path = hass.config.path(PANEL_DIR, f"{name}.html")
if CONF_JS_URL in panel:
kwargs["js_url"] = panel[CONF_JS_URL]

View File

@ -286,7 +286,7 @@ class PhilipsTV(MediaPlayerDevice):
self._tv.update()
self._sources = {
srcid: source["name"] or "Source {}".format(srcid)
srcid: source["name"] or f"Source {srcid}"
for srcid, source in (self._tv.sources or {}).items()
}

View File

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

View File

@ -54,7 +54,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
hass.data["pjlink"] = {}
hass_data = hass.data["pjlink"]
device_label = "{}:{}".format(host, port)
device_label = f"{host}:{port}"
if device_label in hass_data:
return
@ -65,7 +65,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
def format_input_source(input_source_name, input_source_number):
"""Format input source for display in UI."""
return "{} {}".format(input_source_name, input_source_number)
return f"{input_source_name} {input_source_number}"
class PjLinkDevice(MediaPlayerDevice):

View File

@ -37,8 +37,8 @@ ATTR_ABV = "abv"
ATTR_CO2_VOLUME = "co2_volume"
ATTR_BATCH_VOLUME = "batch_volume"
SENSOR_UPDATE = "{}_sensor_update".format(DOMAIN)
SENSOR_DATA_KEY = "{}.{}".format(DOMAIN, SENSOR)
SENSOR_UPDATE = f"{DOMAIN}_sensor_update"
SENSOR_DATA_KEY = f"{DOMAIN}.{SENSOR}"
WEBHOOK_SCHEMA = vol.Schema(
{
@ -121,7 +121,7 @@ async def handle_webhook(hass, webhook_id, request):
async_dispatcher_send(hass, SENSOR_UPDATE, device_id)
return web.Response(text="Saving status for {}".format(device_id), status=HTTP_OK)
return web.Response(text=f"Saving status for {device_id}", status=HTTP_OK)
def _device_id(data):

View File

@ -54,9 +54,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
async_add_entities(entities, True)
else:
for entity in devices[device_id]:
async_dispatcher_send(
hass, "{}_{}".format(PLAATO_DOMAIN, entity.unique_id)
)
async_dispatcher_send(hass, f"{PLAATO_DOMAIN}_{entity.unique_id}")
hass.data[SENSOR_DATA_KEY] = async_dispatcher_connect(
hass, SENSOR_UPDATE, _update_sensor
@ -73,18 +71,18 @@ class PlaatoSensor(Entity):
self._device_id = device_id
self._type = sensor_type
self._state = 0
self._name = "{} {}".format(device_id, sensor_type)
self._name = f"{device_id} {sensor_type}"
self._attributes = None
@property
def name(self):
"""Return the name of the sensor."""
return "{} {}".format(PLAATO_DOMAIN, self._name)
return f"{PLAATO_DOMAIN} {self._name}"
@property
def unique_id(self):
"""Return the unique ID of this sensor."""
return "{}_{}".format(self._device_id, self._type)
return f"{self._device_id}_{self._type}"
@property
def device_info(self):
@ -157,6 +155,5 @@ class PlaatoSensor(Entity):
async def async_added_to_hass(self):
"""Register callbacks."""
self.hass.helpers.dispatcher.async_dispatcher_connect(
"{}_{}".format(PLAATO_DOMAIN, self.unique_id),
self.async_schedule_update_ha_state,
f"{PLAATO_DOMAIN}_{self.unique_id}", self.async_schedule_update_ha_state
)

View File

@ -216,7 +216,7 @@ class Plant(Entity):
)
else:
raise HomeAssistantError(
"Unknown reading from sensor {}: {}".format(entity_id, value)
f"Unknown reading from sensor {entity_id}: {value}"
)
if ATTR_UNIT_OF_MEASUREMENT in new_state.attributes:
self._unit_of_measurement[reading] = new_state.attributes.get(
@ -229,10 +229,10 @@ class Plant(Entity):
result = []
for sensor_name in self._sensormap.values():
params = self.READINGS[sensor_name]
value = getattr(self, "_{}".format(sensor_name))
value = getattr(self, f"_{sensor_name}")
if value is not None:
if value == STATE_UNAVAILABLE:
result.append("{} unavailable".format(sensor_name))
result.append(f"{sensor_name} unavailable")
else:
if sensor_name == READING_BRIGHTNESS:
result.append(
@ -260,14 +260,14 @@ class Plant(Entity):
if "min" in params and params["min"] in self._config:
min_value = self._config[params["min"]]
if value < min_value:
return "{} low".format(sensor_name)
return f"{sensor_name} low"
def _check_max(self, sensor_name, value, params):
"""If configured, check the value against the defined maximum value."""
if "max" in params and params["max"] in self._config:
max_value = self._config[params["max"]]
if value > max_value:
return "{} high".format(sensor_name)
return f"{sensor_name} high"
return None
async def async_added_to_hass(self):
@ -352,7 +352,7 @@ class Plant(Entity):
}
for reading in self._sensormap.values():
attrib[reading] = getattr(self, "_{}".format(reading))
attrib[reading] = getattr(self, f"_{reading}")
if self._brightness_history.max is not None:
attrib[ATTR_MAX_BRIGHTNESS_HISTORY] = self._brightness_history.max

View File

@ -82,7 +82,7 @@ def setup_platform(hass, config, add_entities_callback, discovery_info=None):
# Parse discovery data
host = discovery_info.get("host")
port = discovery_info.get("port")
host = "%s:%s" % (host, port)
host = f"{host}:{port}"
_LOGGER.info("Discovered PLEX server: %s", host)
if host in _CONFIGURING:
@ -113,7 +113,7 @@ def setup_plexserver(
cert_session.verify = False
try:
plexserver = plexapi.server.PlexServer(
"%s://%s" % (http_prefix, host), token, cert_session
f"{http_prefix}://{host}", token, cert_session
)
_LOGGER.info("Discovery configuration done (no token needed)")
except (
@ -847,7 +847,7 @@ class PlexClient(MediaPlayerDevice):
show = self.device.server.library.section(library_name).get(show_name)
if not season_number:
playlist_name = "{} - {} Episodes".format(self.entity_id, show_name)
playlist_name = f"{self.entity_id} - {show_name} Episodes"
return self.device.server.createPlaylist(playlist_name, show.episodes())
for season in show.seasons():

View File

@ -150,7 +150,7 @@ class PlexSensor(Entity):
for sess in sessions:
user = sess.usernames[0]
device = sess.players[0].title
now_playing_user = "{0} - {1}".format(user, device)
now_playing_user = f"{user} - {device}"
now_playing_title = ""
if sess.TYPE == "episode":
@ -161,7 +161,7 @@ class PlexSensor(Entity):
season_title += " ({0})".format(sess.show().year)
season_episode = "S{0}".format(sess.parentIndex)
if sess.index is not None:
season_episode += " · E{0}".format(sess.index)
season_episode += f" · E{sess.index}"
episode_title = sess.title
now_playing_title = "{0} - {1} - {2}".format(
season_title, season_episode, episode_title
@ -181,7 +181,7 @@ class PlexSensor(Entity):
# "The Incredible Hulk (2008)"
now_playing_title = sess.title
if sess.year is not None:
now_playing_title += " ({0})".format(sess.year)
now_playing_title += f" ({sess.year})"
now_playing.append((now_playing_user, now_playing_title))
self._state = len(sessions)

View File

@ -94,7 +94,7 @@ class GlowRing(Light):
def __init__(self, lightpad):
"""Initialize the light."""
self._lightpad = lightpad
self._name = "{} Glow Ring".format(lightpad.friendly_name)
self._name = f"{lightpad.friendly_name} Glow Ring"
self._state = lightpad.glow_enabled
self._brightness = lightpad.glow_intensity * 255.0

View File

@ -182,7 +182,7 @@ class MinutPointClient:
async def new_device(device_id, component):
"""Load new device."""
config_entries_key = "{}.{}".format(component, DOMAIN)
config_entries_key = f"{component}.{DOMAIN}"
async with self._hass.data[DATA_CONFIG_ENTRY_LOCK]:
if config_entries_key not in self._hass.data[CONFIG_ENTRY_IS_SETUP]:
await self._hass.config_entries.async_forward_entry_setup(
@ -247,7 +247,7 @@ class MinutPointEntity(Entity):
def __str__(self):
"""Return string representation of device."""
return "MinutPoint {}".format(self.name)
return f"MinutPoint {self.name}"
async def async_added_to_hass(self):
"""Call when entity is added to hass."""
@ -333,7 +333,7 @@ class MinutPointEntity(Entity):
@property
def unique_id(self):
"""Return the unique id of the sensor."""
return "point.{}-{}".format(self._id, self.device_class)
return f"point.{self._id}-{self.device_class}"
@property
def value(self):

View File

@ -108,7 +108,7 @@ class MinutPointAlarmControl(AlarmControlPanel):
@property
def unique_id(self):
"""Return the unique id of the sensor."""
return "point.{}".format(self._home_id)
return f"point.{self._home_id}"
@property
def device_info(self):

View File

@ -77,7 +77,7 @@ class PrezziBenzinaSensor(Entity):
self._index = index
self._data = None
self._station = station
self._name = "{} {} {}".format(name, ft, srv)
self._name = f"{name} {ft} {srv}"
@property
def name(self):

View File

@ -71,7 +71,7 @@ def setup_proximity_component(hass, name, config):
zone_id,
unit_of_measurement,
)
proximity.entity_id = "{}.{}".format(DOMAIN, proximity_zone)
proximity.entity_id = f"{DOMAIN}.{proximity_zone}"
proximity.schedule_update_ha_state()

View File

@ -156,7 +156,7 @@ async def async_migrate_entry(hass, entry):
def format_unique_id(creds, mac_address):
"""Use last 4 Chars of credential as suffix. Unique ID per PSN user."""
suffix = creds[-4:]
return "{}_{}".format(mac_address, suffix)
return f"{mac_address}_{suffix}"
def load_games(hass: HomeAssistantType) -> dict:

View File

@ -61,9 +61,7 @@ class PushettaNotificationService(BaseNotificationService):
title = kwargs.get(ATTR_TITLE, ATTR_TITLE_DEFAULT)
try:
self.pushetta.pushMessage(
self._channel_name, "{} {}".format(title, message)
)
self.pushetta.pushMessage(self._channel_name, f"{title} {message}")
except exceptions.TokenValidationError:
_LOGGER.error("Please check your access token")
self.is_valid = False

View File

@ -132,7 +132,7 @@ class PushsaferNotificationService(BaseNotificationService):
return None
base64_image = base64.b64encode(filebyte).decode("utf8")
return "data:{};base64,{}".format(mimetype, base64_image)
return f"data:{mimetype};base64,{base64_image}"
def load_from_url(self, url=None, username=None, password=None, auth=None):
"""Load image/document/etc from URL."""

View File

@ -55,7 +55,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD)
monitored_types = config.get(CONF_MONITORED_VARIABLES)
url = "http{}://{}:{}/api/".format(ssl, host, port)
url = f"http{ssl}://{host}:{port}/api/"
try:
pyloadapi = PyLoadAPI(api_url=url, username=username, password=password)

View File

@ -88,7 +88,7 @@ class QBittorrentSensor(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

@ -215,8 +215,8 @@ class QNAPSensor(Entity):
server_name = self._api.data["system_stats"]["system"]["name"]
if self.monitor_device is not None:
return "{} {} ({})".format(server_name, self.var_name, self.monitor_device)
return "{} {}".format(server_name, self.var_name)
return f"{server_name} {self.var_name} ({self.monitor_device})"
return f"{server_name} {self.var_name}"
@property
def icon(self):
@ -270,7 +270,7 @@ class QNAPMemorySensor(QNAPSensor):
if self._api.data:
data = self._api.data["system_stats"]["memory"]
size = round_nicely(float(data["total"]) / 1024)
return {ATTR_MEMORY_SIZE: "{} GB".format(size)}
return {ATTR_MEMORY_SIZE: f"{size} GB"}
class QNAPNetworkSensor(QNAPSensor):
@ -331,7 +331,7 @@ class QNAPSystemSensor(QNAPSensor):
ATTR_NAME: data["system"]["name"],
ATTR_MODEL: data["system"]["model"],
ATTR_SERIAL: data["system"]["serial_number"],
ATTR_UPTIME: "{:0>2d}d {:0>2d}h {:0>2d}m".format(days, hours, minutes),
ATTR_UPTIME: f"{days:0>2d}d {hours:0>2d}h {minutes:0>2d}m",
}

View File

@ -80,7 +80,7 @@ class QSEntity(Entity):
@property
def unique_id(self):
"""Return a unique identifier for this sensor."""
return "qs{}".format(self.qsid)
return f"qs{self.qsid}"
@callback
def update_packet(self, packet):

View File

@ -61,7 +61,7 @@ class QSBinarySensor(QSEntity, BinarySensorDevice):
@property
def unique_id(self):
"""Return a unique identifier for this sensor."""
return "qs{}:{}".format(self.qsid, self.channel)
return f"qs{self.qsid}:{self.channel}"
@property
def device_class(self):

View File

@ -34,7 +34,7 @@ class QSSensor(QSEntity):
self._decode, self.unit = SENSORS[sensor_type]
if isinstance(self.unit, type):
self.unit = "{}:{}".format(sensor_type, self.channel)
self.unit = f"{sensor_type}:{self.channel}"
@callback
def update_packet(self, packet):
@ -60,7 +60,7 @@ class QSSensor(QSEntity):
@property
def unique_id(self):
"""Return a unique identifier for this sensor."""
return "qs{}:{}".format(self.qsid, self.channel)
return f"qs{self.qsid}:{self.channel}"
@property
def unit_of_measurement(self):