Use literal string interpolation in integrations K-M (f-strings) (#26389)

This commit is contained in:
Franck Nijhof 2019-09-03 21:14:00 +02:00 committed by Pascal Vizeli
parent ef0e9431b6
commit 7203027cbf
51 changed files with 104 additions and 121 deletions

View File

@ -66,7 +66,7 @@ class KankunSwitch(SwitchDevice):
self._hass = hass
self._name = name
self._state = False
self._url = "http://{}:{}{}".format(host, port, path)
self._url = f"http://{host}:{port}{path}"
if user is not None:
self._auth = (user, passwd)
else:
@ -78,7 +78,7 @@ class KankunSwitch(SwitchDevice):
try:
req = requests.get(
"{}?set={}".format(self._url, newstate), auth=self._auth, timeout=5
f"{self._url}?set={newstate}", auth=self._auth, timeout=5
)
return req.json()["ok"]
except requests.RequestException:
@ -89,9 +89,7 @@ class KankunSwitch(SwitchDevice):
_LOGGER.info("Querying state from: %s", self._url)
try:
req = requests.get(
"{}?get=state".format(self._url), auth=self._auth, timeout=5
)
req = requests.get(f"{self._url}?get=state", auth=self._auth, timeout=5)
return req.json()["state"] == "on"
except requests.RequestException:
_LOGGER.error("State query failed")

View File

@ -32,7 +32,7 @@ CONF_REMOTES = "remotes"
CONF_SENSOR = "sensor"
CONF_REMOTE = "remote"
CODES_YAML = "{}_codes.yaml".format(DOMAIN)
CODES_YAML = f"{DOMAIN}_codes.yaml"
CODE_SCHEMA = vol.Schema(
{

View File

@ -140,7 +140,7 @@ def _check_deprecated_turn_off(hass, turn_off_action):
method = DEPRECATED_TURN_OFF_ACTIONS[turn_off_action]
new_config = OrderedDict(
[
("service", "{}.{}".format(DOMAIN, SERVICE_CALL_METHOD)),
("service", f"{DOMAIN}.{SERVICE_CALL_METHOD}"),
(
"data_template",
OrderedDict([("entity_id", "{{ entity_id }}"), ("method", method)]),
@ -281,18 +281,18 @@ class KodiDevice(MediaPlayerDevice):
if username is not None:
kwargs["auth"] = aiohttp.BasicAuth(username, password)
image_auth_string = "{}:{}@".format(username, password)
image_auth_string = f"{username}:{password}@"
else:
image_auth_string = ""
http_protocol = "https" if encryption else "http"
ws_protocol = "wss" if encryption else "ws"
self._http_url = "{}://{}:{}/jsonrpc".format(http_protocol, host, port)
self._http_url = f"{http_protocol}://{host}:{port}/jsonrpc"
self._image_url = "{}://{}{}:{}/image".format(
http_protocol, image_auth_string, host, port
)
self._ws_url = "{}://{}:{}/jsonrpc".format(ws_protocol, host, tcp_port)
self._ws_url = f"{ws_protocol}://{host}:{tcp_port}/jsonrpc"
self._http_server = jsonrpc_async.Server(self._http_url, **kwargs)
if websocket:
@ -326,14 +326,14 @@ class KodiDevice(MediaPlayerDevice):
turn_on_action = script.Script(
self.hass,
turn_on_action,
"{} turn ON script".format(self.name),
f"{self.name} turn ON script",
self.async_update_ha_state(True),
)
if turn_off_action is not None:
turn_off_action = script.Script(
self.hass,
_check_deprecated_turn_off(hass, turn_off_action),
"{} turn OFF script".format(self.name),
f"{self.name} turn OFF script",
)
self._turn_on_action = turn_on_action
self._turn_off_action = turn_off_action

View File

@ -62,7 +62,7 @@ async def async_get_service(hass, config, discovery_info=None):
)
http_protocol = "https" if encryption else "http"
url = "{}://{}:{}/jsonrpc".format(http_protocol, host, port)
url = f"{http_protocol}://{host}:{port}/jsonrpc"
if username is not None:
auth = aiohttp.BasicAuth(username, password)

View File

@ -538,7 +538,7 @@ class KonnectedView(HomeAssistantView):
)
auth = request.headers.get(AUTHORIZATION, None)
if not hmac.compare_digest("Bearer {}".format(self.auth_token), auth):
if not hmac.compare_digest(f"Bearer {self.auth_token}", auth):
return self.json_message("unauthorized", status_code=HTTP_UNAUTHORIZED)
pin_num = int(pin_num)
device = data[CONF_DEVICES].get(device_id)

View File

@ -92,7 +92,7 @@ class KWBSensor(Entity):
@property
def name(self):
"""Return the name."""
return "{} {}".format(self._client_name, self._name)
return f"{self._client_name} {self._name}"
@property
def available(self) -> bool:

View File

@ -72,7 +72,7 @@ class LastfmSensor(Entity):
@property
def entity_id(self):
"""Return the entity ID."""
return "sensor.lastfm_{}".format(self._name)
return f"sensor.lastfm_{self._name}"
@property
def state(self):
@ -84,7 +84,7 @@ class LastfmSensor(Entity):
self._cover = self._user.get_image()
self._playcount = self._user.get_playcount()
last = self._user.get_recent_tracks(limit=2)[0]
self._lastplayed = "{} - {}".format(last.track.artist, last.track.title)
self._lastplayed = f"{last.track.artist} - {last.track.title}"
top = self._user.get_top_tracks(limit=1)[0]
toptitle = re.search("', '(.+?)',", str(top))
topartist = re.search("'(.+?)',", str(top))
@ -93,7 +93,7 @@ class LastfmSensor(Entity):
self._state = "Not Scrobbling"
return
now = self._user.get_now_playing()
self._state = "{} - {}".format(now.artist, now.title)
self._state = f"{now.artist} - {now.title}"
@property
def device_state_attributes(self):

View File

@ -38,7 +38,7 @@ def has_unique_connection_names(connections):
if suffix == 0:
connection[CONF_NAME] = DEFAULT_NAME
else:
connection[CONF_NAME] = "{}{:d}".format(DEFAULT_NAME, suffix)
connection[CONF_NAME] = f"{DEFAULT_NAME}{suffix:d}"
schema = vol.Schema(vol.Unique())
schema([connection.get(CONF_NAME) for connection in connections])

View File

@ -99,7 +99,7 @@ class Life360ConfigFlow(config_entries.ConfigFlow):
)
return self.async_abort(reason="unexpected")
return self.async_create_entry(
title="{} (from configuration)".format(username),
title=f"{username} (from configuration)",
data={
CONF_USERNAME: username,
CONF_PASSWORD: password,

View File

@ -159,7 +159,7 @@ class Life360Scanner:
_errs = self._errs.get(key, 0)
if _errs < self._max_errs:
self._errs[key] = _errs = _errs + 1
msg = "{}: {}".format(key, err_msg)
msg = f"{key}: {err_msg}"
if _errs >= self._error_threshold:
if _errs == self._max_errs:
msg = "Suppressing further errors until OK: " + msg
@ -233,14 +233,12 @@ class Life360Scanner:
convert(float(gps_accuracy), LENGTH_FEET, LENGTH_METERS)
)
except (TypeError, ValueError):
self._err(
dev_id, "GPS data invalid: {}, {}, {}".format(lat, lon, gps_accuracy)
)
self._err(dev_id, f"GPS data invalid: {lat}, {lon}, {gps_accuracy}")
return
self._ok(dev_id)
msg = "Updating {}".format(dev_id)
msg = f"Updating {dev_id}"
if prev_seen:
msg += "; Time since last update: {}".format(last_seen - prev_seen)
_LOGGER.debug(msg)
@ -401,7 +399,7 @@ class Life360Scanner:
except (Life360Error, KeyError):
pass
if incl_circle:
err_key = 'get_circle_members "{}"'.format(circle_name)
err_key = f'get_circle_members "{circle_name}"'
try:
members = api.get_circle_members(circle_id)
except Life360Error as exc:

View File

@ -509,7 +509,7 @@ class LIFXLight(Light):
@property
def who(self):
"""Return a string identifying the bulb."""
return "%s (%s)" % (self.bulb.ip_addr, self.name)
return f"{self.bulb.ip_addr} ({self.name})"
@property
def min_mireds(self):

View File

@ -31,7 +31,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
token = config.get(CONF_TOKEN)
timeout = config.get(CONF_TIMEOUT)
headers = {AUTHORIZATION: "Bearer {}".format(token)}
headers = {AUTHORIZATION: f"Bearer {token}"}
url = LIFX_API_URL.format("scenes")

View File

@ -237,16 +237,16 @@ class SetIntentHandler(intent.IntentHandler):
response = intent_obj.create_response()
if not speech_parts: # No attributes changed
speech = "Turned on {}".format(state.name)
speech = f"Turned on {state.name}"
else:
parts = ["Changed {} to".format(state.name)]
parts = [f"Changed {state.name} to"]
for index, part in enumerate(speech_parts):
if index == 0:
parts.append(" {}".format(part))
parts.append(f" {part}")
elif index != len(speech_parts) - 1:
parts.append(", {}".format(part))
parts.append(f", {part}")
else:
parts.append(" and {}".format(part))
parts.append(f" and {part}")
speech = "".join(parts)
response.async_set_speech(speech)

View File

@ -100,7 +100,7 @@ class LinksysSmartWifiDeviceScanner(DeviceScanner):
]
headers = {"X-JNAP-Action": "http://linksys.com/jnap/core/Transaction"}
return requests.post(
"http://{}/JNAP/".format(self.host),
f"http://{self.host}/JNAP/",
timeout=DEFAULT_TIMEOUT,
headers=headers,
json=data,

View File

@ -59,7 +59,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
if system == "android":
os.listdir(os.path.join(DEFAULT_PATH, "battery"))
else:
os.listdir(os.path.join(DEFAULT_PATH, "BAT{}".format(battery_id)))
os.listdir(os.path.join(DEFAULT_PATH, f"BAT{battery_id}"))
except FileNotFoundError:
_LOGGER.error("No battery found")
return False

View File

@ -178,7 +178,7 @@ class LiveboxPlayTvDevice(MediaPlayerDevice):
"""Title of current playing media."""
if self._current_channel:
if self._current_program:
return "{}: {}".format(self._current_channel, self._current_program)
return f"{self._current_channel}: {self._current_program}"
return self._current_channel
@property

View File

@ -22,7 +22,7 @@ from homeassistant.helpers.dispatcher import async_dispatcher_send
_LOGGER = logging.getLogger(__name__)
DOMAIN = "locative"
TRACKER_UPDATE = "{}_tracker_update".format(DOMAIN)
TRACKER_UPDATE = f"{DOMAIN}_tracker_update"
ATTR_DEVICE_ID = "device"
@ -76,12 +76,10 @@ async def handle_webhook(hass, webhook_id, request):
if direction == "enter":
async_dispatcher_send(hass, TRACKER_UPDATE, device, gps_location, location_name)
return web.Response(
text="Setting location to {}".format(location_name), status=HTTP_OK
)
return web.Response(text=f"Setting location to {location_name}", status=HTTP_OK)
if direction == "exit":
current_state = hass.states.get("{}.{}".format(DEVICE_TRACKER, device))
current_state = hass.states.get(f"{DEVICE_TRACKER}.{device}")
if current_state is None or current_state.state == location_name:
location_name = STATE_NOT_HOME
@ -108,7 +106,7 @@ async def handle_webhook(hass, webhook_id, request):
_LOGGER.error("Received unidentified message from Locative: %s", direction)
return web.Response(
text="Received unidentified message: {}".format(direction),
text=f"Received unidentified message: {direction}",
status=HTTP_UNPROCESSABLE_ENTITY,
)

View File

@ -188,7 +188,7 @@ def humanify(hass, events):
- if 2+ sensor updates in GROUP_BY_MINUTES, show last
- if home assistant stop and start happen in same minute call it restarted
"""
domain_prefixes = tuple("{}.".format(dom) for dom in CONTINUOUS_DOMAINS)
domain_prefixes = tuple(f"{dom}." for dom in CONTINUOUS_DOMAINS)
# Group events in batches of GROUP_BY_MINUTES
for _, g_events in groupby(
@ -332,7 +332,7 @@ def humanify(hass, events):
entity_id = data.get(ATTR_ENTITY_ID)
value = data.get(ATTR_VALUE)
value_msg = " to {}".format(value) if value else ""
value_msg = f" to {value}" if value else ""
message = "send command {}{} for {}".format(
data[ATTR_SERVICE], value_msg, data[ATTR_DISPLAY_NAME]
)
@ -519,7 +519,7 @@ def _keep_event(event, entities_filter):
domain = DOMAIN_HOMEKIT
if not entity_id and domain:
entity_id = "%s." % (domain,)
entity_id = f"{domain}."
return not entity_id or entities_filter(entity_id)
@ -530,7 +530,7 @@ def _entry_message_from_state(domain, state):
if domain in ["device_tracker", "person"]:
if state.state == STATE_NOT_HOME:
return "is away"
return "is at {}".format(state.state)
return f"is at {state.state}"
if domain == "sun":
if state.state == sun.STATE_ABOVE_HORIZON:
@ -596,9 +596,9 @@ def _entry_message_from_state(domain, state):
"vibration",
]:
if state.state == STATE_ON:
return "detected {}".format(device_class)
return f"detected {device_class}"
if state.state == STATE_OFF:
return "cleared (no {} detected)".format(device_class)
return f"cleared (no {device_class} detected)"
if state.state == STATE_ON:
# Future: combine groups and its entity entries ?
@ -607,4 +607,4 @@ def _entry_message_from_state(domain, state):
if state.state == STATE_OFF:
return "turned off"
return "changed to {}".format(state.state)
return f"changed to {state.state}"

View File

@ -24,7 +24,7 @@ def setup(hass, config):
"""Set up the Logentries component."""
conf = config[DOMAIN]
token = conf.get(CONF_TOKEN)
le_wh = "{}{}".format(DEFAULT_HOST, token)
le_wh = f"{DEFAULT_HOST}{token}"
def logentries_event_listener(event):
"""Listen for new messages on the bus and sends them to Logentries."""

View File

@ -156,7 +156,7 @@ async def async_setup_entry(hass, entry):
except asyncio.TimeoutError:
# The TimeoutError exception object returns nothing when casted to a
# string, so we'll handle it separately.
err = "{}s timeout exceeded when connecting to Logi Circle API".format(_TIMEOUT)
err = f"{_TIMEOUT}s timeout exceeded when connecting to Logi Circle API"
hass.components.persistent_notification.create(
"Error: {}<br />"
"You will need to restart hass after fixing."

View File

@ -179,7 +179,7 @@ class LogiCircleFlowHandler(config_entries.ConfigFlow):
account_id = (await logi_session.account)["accountId"]
await logi_session.close()
return self.async_create_entry(
title="Logi Circle ({})".format(account_id),
title=f"Logi Circle ({account_id})",
data={
CONF_CLIENT_ID: client_id,
CONF_CLIENT_SECRET: client_secret,

View File

@ -49,7 +49,7 @@ class LogiSensor(Entity):
"""Initialize a sensor for Logi Circle camera."""
self._sensor_type = sensor_type
self._camera = camera
self._id = "{}-{}".format(self._camera.mac_address, self._sensor_type)
self._id = f"{self._camera.mac_address}-{self._sensor_type}"
self._icon = "mdi:{}".format(SENSOR_TYPES.get(self._sensor_type)[2])
self._name = "{0} {1}".format(
self._camera.name, SENSOR_TYPES.get(self._sensor_type)[0]

View File

@ -34,7 +34,7 @@ SENSOR_PM2_5 = "P2"
SENSOR_PRESSURE = "pressure"
SENSOR_TEMPERATURE = "temperature"
TOPIC_UPDATE = "{0}_data_update".format(DOMAIN)
TOPIC_UPDATE = f"{DOMAIN}_data_update"
VOLUME_MICROGRAMS_PER_CUBIC_METER = "µg/m3"

View File

@ -114,7 +114,7 @@ class LutronDevice(Entity):
@property
def name(self):
"""Return the name of the device."""
return "{} {}".format(self._area_name, self._lutron_device.name)
return f"{self._area_name} {self._lutron_device.name}"
@property
def should_poll(self):
@ -132,7 +132,7 @@ class LutronButton:
def __init__(self, hass, keypad, button):
"""Register callback for activity on the button."""
name = "{}: {}".format(keypad.name, button.name)
name = f"{keypad.name}: {button.name}"
self._hass = hass
self._has_release_event = (
button.button_type is not None and "RaiseLower" in button.button_type

View File

@ -85,7 +85,7 @@ class LyftSensor(Entity):
self._sensortype = sensorType
self._name = "{} {}".format(self._product["display_name"], self._sensortype)
if "lyft" not in self._name.lower():
self._name = "Lyft{}".format(self._name)
self._name = f"Lyft{self._name}"
if self._sensortype == "time":
self._unit_of_measurement = "min"
elif self._sensortype == "price":

View File

@ -108,10 +108,10 @@ class MagicSeaweedSensor(Entity):
def name(self):
"""Return the name of the sensor."""
if self.hour is None and "forecast" in self.type:
return "{} {}".format(self.client_name, self._name)
return f"{self.client_name} {self._name}"
if self.hour is None:
return "Current {} {}".format(self.client_name, self._name)
return "{} {} {}".format(self.hour, self.client_name, self._name)
return f"Current {self.client_name} {self._name}"
return f"{self.hour} {self.client_name} {self._name}"
@property
def state(self):

View File

@ -19,7 +19,7 @@ CONF_SANDBOX = "sandbox"
DEFAULT_SANDBOX = False
MESSAGE_RECEIVED = "{}_message_received".format(DOMAIN)
MESSAGE_RECEIVED = f"{DOMAIN}_message_received"
CONFIG_SCHEMA = vol.Schema(
{
@ -75,7 +75,7 @@ async def verify_webhook(hass, token=None, timestamp=None, signature=None):
hmac_digest = hmac.new(
key=bytes(hass.data[DOMAIN][CONF_API_KEY], "utf-8"),
msg=bytes("{}{}".format(timestamp, token), "utf-8"),
msg=bytes(f"{timestamp}{token}", "utf-8"),
digestmod=hashlib.sha256,
).hexdigest()

View File

@ -74,7 +74,7 @@ class MaryTTSProvider(Provider):
try:
with async_timeout.timeout(10):
url = "http://{}:{}/process?".format(self._host, self._port)
url = f"http://{self._host}:{self._port}/process?"
audio = self._codec.upper()
if audio == "WAV":

View File

@ -83,7 +83,7 @@ class MetOfficeWeather(WeatherEntity):
@property
def name(self):
"""Return the name of the sensor."""
return "{} {}".format(self._name, self.site.name)
return f"{self._name} {self.site.name}"
@property
def condition(self):

View File

@ -115,8 +115,8 @@ class MicrosoftProvider(Provider):
self._gender = gender
self._type = ttype
self._output = DEFAULT_OUTPUT
self._rate = "{}%".format(rate)
self._volume = "{}%".format(volume)
self._rate = f"{rate}%"
self._volume = f"{volume}%"
self._pitch = pitch
self._contour = contour
self.name = "Microsoft"

View File

@ -92,7 +92,7 @@ async def async_setup(hass, config):
g_id = slugify(name)
try:
await face.call_api("put", "persongroups/{0}".format(g_id), {"name": name})
await face.call_api("put", f"persongroups/{g_id}", {"name": name})
face.store[g_id] = {}
entities[g_id] = MicrosoftFaceGroupEntity(hass, face, g_id, name)
@ -109,7 +109,7 @@ async def async_setup(hass, config):
g_id = slugify(service.data[ATTR_NAME])
try:
await face.call_api("delete", "persongroups/{0}".format(g_id))
await face.call_api("delete", f"persongroups/{g_id}")
face.store.pop(g_id)
entity = entities.pop(g_id)
@ -126,7 +126,7 @@ async def async_setup(hass, config):
g_id = service.data[ATTR_GROUP]
try:
await face.call_api("post", "persongroups/{0}/train".format(g_id))
await face.call_api("post", f"persongroups/{g_id}/train")
except HomeAssistantError as err:
_LOGGER.error("Can't train group '%s' with error: %s", g_id, err)
@ -141,7 +141,7 @@ async def async_setup(hass, config):
try:
user_data = await face.call_api(
"post", "persongroups/{0}/persons".format(g_id), {"name": name}
"post", f"persongroups/{g_id}/persons", {"name": name}
)
face.store[g_id][name] = user_data["personId"]
@ -160,9 +160,7 @@ async def async_setup(hass, config):
p_id = face.store[g_id].get(name)
try:
await face.call_api(
"delete", "persongroups/{0}/persons/{1}".format(g_id, p_id)
)
await face.call_api("delete", f"persongroups/{g_id}/persons/{p_id}")
face.store[g_id].pop(name)
await entities[g_id].async_update_ha_state()
@ -186,7 +184,7 @@ async def async_setup(hass, config):
await face.call_api(
"post",
"persongroups/{0}/persons/{1}/persistedFaces".format(g_id, p_id),
f"persongroups/{g_id}/persons/{p_id}/persistedFaces",
image.content,
binary=True,
)
@ -218,7 +216,7 @@ class MicrosoftFaceGroupEntity(Entity):
@property
def entity_id(self):
"""Return entity id."""
return "{0}.{1}".format(DOMAIN, self._id)
return f"{DOMAIN}.{self._id}"
@property
def state(self):
@ -249,7 +247,7 @@ class MicrosoftFace:
self.websession = async_get_clientsession(hass)
self.timeout = timeout
self._api_key = api_key
self._server_url = "https://{0}.{1}".format(server_loc, FACE_API_URL)
self._server_url = f"https://{server_loc}.{FACE_API_URL}"
self._store = {}
self._entities = entities
@ -270,9 +268,7 @@ class MicrosoftFace:
self.hass, self, g_id, group["name"]
)
persons = await self.call_api(
"get", "persongroups/{0}/persons".format(g_id)
)
persons = await self.call_api("get", f"persongroups/{g_id}/persons")
for person in persons:
self._store[g_id][person["name"]] = person["personId"]

View File

@ -30,7 +30,7 @@ def validate_attributes(list_attributes):
"""Validate face attributes."""
for attr in list_attributes:
if attr not in SUPPORTED_ATTRIBUTES:
raise vol.Invalid("Invalid attribute {0}".format(attr))
raise vol.Invalid(f"Invalid attribute {attr}")
return list_attributes

View File

@ -85,7 +85,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
prefix = config.get(CONF_NAME)
if prefix:
name = "{} {}".format(prefix, name)
name = f"{prefix} {name}"
devs.append(
MiFloraSensor(poller, parameter, name, unit, icon, force_update, median)

View File

@ -166,7 +166,7 @@ def setup(hass, config):
def get_minio_endpoint(host: str, port: int) -> str:
"""Create minio endpoint from host and port."""
return "{}:{}".format(host, port)
return f"{host}:{port}"
class QueueListener(threading.Thread):

View File

@ -94,7 +94,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
prefix = config.get(CONF_NAME)
if prefix:
name = "{} {}".format(prefix, name)
name = f"{prefix} {name}"
devs.append(
MiTempBtSensor(poller, parameter, device, name, unit, force_update, median)

View File

@ -53,7 +53,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
async_dispatcher_connect(
hass,
"{}_{}_register".format(DOMAIN, ENTITY_TYPE),
f"{DOMAIN}_{ENTITY_TYPE}_register",
partial(handle_sensor_registration, webhook_id),
)

View File

@ -21,7 +21,7 @@ from .helpers import device_info
def sensor_id(webhook_id, unique_id):
"""Return a unique sensor ID."""
return "{}_{}".format(webhook_id, unique_id)
return f"{webhook_id}_{unique_id}"
class MobileAppEntity(Entity):

View File

@ -53,7 +53,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
async_dispatcher_connect(
hass,
"{}_{}_register".format(DOMAIN, ENTITY_TYPE),
f"{DOMAIN}_{ENTITY_TYPE}_register",
partial(handle_sensor_registration, webhook_id),
)

View File

@ -220,13 +220,13 @@ async def handle_webhook(
unique_id = data[ATTR_SENSOR_UNIQUE_ID]
unique_store_key = "{}_{}".format(webhook_id, unique_id)
unique_store_key = f"{webhook_id}_{unique_id}"
if unique_store_key in hass.data[DOMAIN][entity_type]:
_LOGGER.error("Refusing to re-register existing sensor %s!", unique_id)
return error_response(
ERR_SENSOR_DUPLICATE_UNIQUE_ID,
"{} {} already exists!".format(entity_type, unique_id),
f"{entity_type} {unique_id} already exists!",
status=409,
)
@ -257,13 +257,13 @@ async def handle_webhook(
unique_id = sensor[ATTR_SENSOR_UNIQUE_ID]
unique_store_key = "{}_{}".format(webhook_id, unique_id)
unique_store_key = f"{webhook_id}_{unique_id}"
if unique_store_key not in hass.data[DOMAIN][entity_type]:
_LOGGER.error(
"Refusing to update non-registered sensor: %s", unique_store_key
)
err_msg = "{} {} is not registered".format(entity_type, unique_id)
err_msg = f"{entity_type} {unique_id} is not registered"
resp[unique_id] = {
"success": False,
"error": {"code": ERR_SENSOR_NOT_REGISTERED, "message": err_msg},

View File

@ -50,7 +50,7 @@ class MochadLight(Light):
self._controller = ctrl
self._address = dev[CONF_ADDRESS]
self._name = dev.get(CONF_NAME, "x10_light_dev_{}".format(self._address))
self._name = dev.get(CONF_NAME, f"x10_light_dev_{self._address}")
self._comm_type = dev.get(mochad.CONF_COMM_TYPE, "pl")
self.light = device.Device(ctrl, self._address, comm_type=self._comm_type)
self._brightness = 0
@ -95,12 +95,12 @@ class MochadLight(Light):
if self._brightness > brightness:
bdelta = self._brightness - brightness
mochad_brightness = self._calculate_brightness_value(bdelta)
self.light.send_cmd("dim {}".format(mochad_brightness))
self.light.send_cmd(f"dim {mochad_brightness}")
self._controller.read_data()
elif self._brightness < brightness:
bdelta = brightness - self._brightness
mochad_brightness = self._calculate_brightness_value(bdelta)
self.light.send_cmd("bright {}".format(mochad_brightness))
self.light.send_cmd(f"bright {mochad_brightness}")
self._controller.read_data()
def turn_on(self, **kwargs):
@ -109,7 +109,7 @@ class MochadLight(Light):
with mochad.REQ_LOCK:
if self._brightness_levels > 32:
out_brightness = self._calculate_brightness_value(brightness)
self.light.send_cmd("xdim {}".format(out_brightness))
self.light.send_cmd(f"xdim {out_brightness}")
self._controller.read_data()
else:
self.light.send_cmd("on")

View File

@ -170,7 +170,7 @@ class ModbusThermostat(ClimateDevice):
[x.to_bytes(2, byteorder="big") for x in result.registers]
)
val = struct.unpack(self._structure, byte_string)[0]
register_value = format(val, ".{}f".format(self._precision))
register_value = format(val, f".{self._precision}f")
return register_value
def write_register(self, register, value):

View File

@ -54,7 +54,7 @@ def number(value: Any) -> Union[int, float]:
value = float(value)
return value
except (TypeError, ValueError):
raise vol.Invalid("invalid number {}".format(value))
raise vol.Invalid(f"invalid number {value}")
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(

View File

@ -19,7 +19,7 @@ from homeassistant.helpers.dispatcher import dispatcher_send
from homeassistant.helpers.event import track_time_interval
DOMAIN = "mopar"
DATA_UPDATED = "{}_data_updated".format(DOMAIN)
DATA_UPDATED = f"{DOMAIN}_data_updated"
_LOGGER = logging.getLogger(__name__)

View File

@ -56,7 +56,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
host = config.get(CONF_HOST)
port = config.get(CONF_PORT)
url = "{}:{}".format(host, port)
url = f"{host}:{port}"
add_entities([MpcHcDevice(name, url)], True)
@ -73,9 +73,7 @@ class MpcHcDevice(MediaPlayerDevice):
def update(self):
"""Get the latest details."""
try:
response = requests.get(
"{}/variables.html".format(self._url), data=None, timeout=3
)
response = requests.get(f"{self._url}/variables.html", data=None, timeout=3)
mpchc_variables = re.findall(r'<p id="(.+?)">(.+?)</p>', response.text)
@ -88,7 +86,7 @@ class MpcHcDevice(MediaPlayerDevice):
"""Send a command to MPC-HC via its window message ID."""
try:
params = {"wm_command": command_id}
requests.get("{}/command.html".format(self._url), params=params, timeout=3)
requests.get(f"{self._url}/command.html", params=params, timeout=3)
except requests.exceptions.RequestException:
_LOGGER.error(
"Could not send command %d to MPC-HC at: %s", command_id, self._url

View File

@ -211,7 +211,7 @@ class MpdDevice(MediaPlayerDevice):
if title is None:
return name
return "{}: {}".format(name, title)
return f"{name}: {title}"
@property
def media_artist(self):

View File

@ -86,7 +86,7 @@ async def async_start(
"""Process the received message."""
payload = msg.payload
topic = msg.topic
topic_trimmed = topic.replace("{}/".format(discovery_topic), "", 1)
topic_trimmed = topic.replace(f"{discovery_topic}/", "", 1)
match = TOPIC_MATCHER.match(topic_trimmed)
if not match:
@ -134,9 +134,7 @@ async def async_start(
if payload:
# Attach MQTT topic to the payload, used for debug prints
setattr(
payload, "__configuration_source__", "MQTT (topic: '{}')".format(topic)
)
setattr(payload, "__configuration_source__", f"MQTT (topic: '{topic}')")
if CONF_PLATFORM in payload and "schema" not in payload:
platform = payload[CONF_PLATFORM]

View File

@ -339,7 +339,7 @@ class MqttVacuum(
elif self._cleaning:
self._status = "Cleaning"
elif self._error:
self._status = "Error: {}".format(self._error)
self._status = f"Error: {self._error}"
else:
self._status = "Stopped"
@ -360,7 +360,7 @@ class MqttVacuum(
self.hass,
self._sub_state,
{
"topic{}".format(i): {
f"topic{i}": {
"topic": topic,
"msg_callback": message_received,
"qos": self._qos,
@ -550,7 +550,7 @@ class MqttVacuum(
mqtt.async_publish(
self.hass, self._set_fan_speed_topic, fan_speed, self._qos, self._retain
)
self._status = "Setting fan to {}...".format(fan_speed)
self._status = f"Setting fan to {fan_speed}..."
self.async_write_ha_state()
async def async_send_command(self, command, params=None, **kwargs):
@ -566,5 +566,5 @@ class MqttVacuum(
mqtt.async_publish(
self.hass, self._send_command_topic, message, self._qos, self._retain
)
self._status = "Sending command {}...".format(message)
self._status = f"Sending command {message}..."
self.async_write_ha_state()

View File

@ -56,7 +56,7 @@ def is_persistence_file(value):
"""Validate that persistence file path ends in either .pickle or .json."""
if value.endswith((".json", ".pickle")):
return value
raise vol.Invalid("{} does not end in either `.json` or `.pickle`".format(value))
raise vol.Invalid(f"{value} does not end in either `.json` or `.pickle`")
def deprecated(key):
@ -138,7 +138,7 @@ def _get_mysensors_name(gateway, node_id, child_id):
),
node_name,
)
return "{} {}".format(node_name, child_id)
return f"{node_name} {child_id}"
@callback

View File

@ -44,7 +44,7 @@ def is_serial_port(value):
ports = ("COM{}".format(idx + 1) for idx in range(256))
if value in ports:
return value
raise vol.Invalid("{} is not a serial port".format(value))
raise vol.Invalid(f"{value} is not a serial port")
return cv.isdevice(value)

View File

@ -26,7 +26,7 @@ class MySensorsNotificationDevice(mysensors.device.MySensorsDevice):
def __repr__(self):
"""Return the representation."""
return "<MySensorsNotificationDevice {}>".format(self.name)
return f"<MySensorsNotificationDevice {self.name}>"
class MySensorsNotificationService(BaseNotificationService):

View File

@ -41,19 +41,16 @@ class MyStromView(HomeAssistantView):
if button_action is None:
_LOGGER.error("Received unidentified message from myStrom button: %s", data)
return (
"Received unidentified message: {}".format(data),
HTTP_UNPROCESSABLE_ENTITY,
)
return (f"Received unidentified message: {data}", HTTP_UNPROCESSABLE_ENTITY)
button_id = data[button_action]
entity_id = "{}.{}_{}".format(DOMAIN, button_id, button_action)
entity_id = f"{DOMAIN}.{button_id}_{button_action}"
if entity_id not in self.buttons:
_LOGGER.info(
"New myStrom button/action detected: %s/%s", button_id, button_action
)
self.buttons[entity_id] = MyStromBinarySensor(
"{}_{}".format(button_id, button_action)
f"{button_id}_{button_action}"
)
self.add_entities([self.buttons[entity_id]])
else: