Improve string formatting v5 (#33697)

* Improve string formatting v5

* Address review comments
This commit is contained in:
springstan authored and GitHub committed 2020-04-05 17:48:55 +02:00
1 parent 39336d3ea3
commit fca90a8ddc
46 files changed
+221 -252

No files matched your search

+1 -3
View File
@@ -191,9 +191,7 @@ class AfterShipSensor(Entity):
"name": name,
"tracking_number": track["tracking_number"],
"slug": track["slug"],
"link": "{}{}/{}".format(
BASE, track["slug"], track["tracking_number"]
),
"link": f"{BASE}{track['slug']}/{track['tracking_number']}",
"last_update": track["updated_at"],
"expected_delivery": track["expected_delivery"],
"status": track["tag"],
+6 -3
View File
@@ -90,8 +90,11 @@ async def async_request_validation(hass, config_entry, august_gateway):
hass.data[DOMAIN][entry_id][TWO_FA_REVALIDATE] = configurator.async_request_config(
f"{DEFAULT_NAME} ({username})",
async_august_configuration_validation_callback,
description="August must be re-verified. Please check your {} ({}) and enter the verification "
"code below".format(login_method, username),
description=(
"August must be re-verified. "
f"Please check your {login_method} ({username}) "
"and enter the verification code below"
),
submit_caption="Verify",
fields=[
{"id": VERIFICATION_CODE_KEY, "name": "Verification code", "type": "string"}
@@ -265,7 +268,7 @@ class AugustData(AugustSubscriberMixin):
self._api.async_get_doorbell_detail,
)
_LOGGER.debug(
"async_signal_device_id_update (from detail updates): %s", device_id,
"async_signal_device_id_update (from detail updates): %s", device_id
)
self.async_signal_device_id_update(device_id)
@@ -92,7 +92,7 @@ def calculate_offset(event, offset):
time = search.group(1)
if ":" not in time:
if time[0] == "+" or time[0] == "-":
time = "{}0:{}".format(time[0], time[1:])
time = f"{time[0]}0:{time[1:]}"
else:
time = f"0:{time}"
+1 -3
View File
@@ -49,9 +49,7 @@ def setup(hass, config):
except (ConnectTimeout, HTTPError) as ex:
_LOGGER.error("Unable to connect to Canary service: %s", str(ex))
hass.components.persistent_notification.create(
"Error: {}<br />"
"You will need to restart hass after fixing."
"".format(ex),
f"Error: {ex}<br />You will need to restart hass after fixing.",
title=NOTIFICATION_TITLE,
notification_id=NOTIFICATION_ID,
)
+1 -1
View File
@@ -76,7 +76,7 @@ class CanarySensor(Entity):
@property
def unique_id(self):
"""Return the unique ID of this sensor."""
return "{}_{}".format(self._device_id, self._sensor_type[0])
return f"{self._device_id}_{self._sensor_type[0]}"
@property
def unit_of_measurement(self):
@@ -48,7 +48,7 @@ class CiscoWebexTeamsNotificationService(BaseNotificationService):
title = ""
if kwargs.get(ATTR_TITLE) is not None:
title = "{}{}".format(kwargs.get(ATTR_TITLE), "<br>")
title = f"{kwargs.get(ATTR_TITLE)}<br>"
try:
self.client.messages.create(roomId=self.room, html=f"{title}{message}")
@@ -119,9 +119,9 @@ class AlexaConfig(alexa_config.AbstractConfig):
if self.should_report_state:
await self._prefs.async_update(alexa_report_state=False)
self.hass.components.persistent_notification.async_create(
"There was an error reporting state to Alexa ({}). "
f"There was an error reporting state to Alexa ({body['reason']}). "
"Please re-link your Alexa skill via the Alexa app to "
"continue using it.".format(body["reason"]),
"continue using it.",
"Alexa state reporting disabled",
"cloud_alexa_report",
)
+1 -1
View File
@@ -82,7 +82,7 @@ class AccountSensor(Entity):
"""Get the latest state of the sensor."""
self._coinbase_data.update()
for account in self._coinbase_data.accounts["data"]:
if self._name == "Coinbase {}".format(account["name"]):
if self._name == f"Coinbase {account['name']}":
self._state = account["balance"]["amount"]
self._native_balance = account["native_balance"]["amount"]
self._native_currency = account["native_balance"]["currency"]
+4 -3
View File
@@ -219,15 +219,16 @@ class HassEzvizCamera(Camera):
ffmpeg = ImageFrame(self._ffmpeg.binary, loop=self.hass.loop)
image = await asyncio.shield(
ffmpeg.get_image(self._rtsp_stream, output_format=IMAGE_JPEG,)
ffmpeg.get_image(self._rtsp_stream, output_format=IMAGE_JPEG)
)
return image
async def stream_source(self):
"""Return the stream source."""
if self._local_rtsp_port:
rtsp_stream_source = "rtsp://{}:{}@{}:{}".format(
self._username, self._password, self._local_ip, self._local_rtsp_port
rtsp_stream_source = (
f"rtsp://{self._username}:{self._password}@"
f"{self._local_ip}:{self._local_rtsp_port}"
)
_LOGGER.debug(
"Camera %s source stream: %s", self._serial, rtsp_stream_source
@@ -67,9 +67,7 @@ class CecPlayerDevice(CecDevice, MediaPlayerDevice):
def __init__(self, device, logical) -> None:
"""Initialize the HDMI device."""
CecDevice.__init__(self, device, logical)
self.entity_id = "{}.{}_{}".format(
DOMAIN, "hdmi", hex(self._logical_address)[2:]
)
self.entity_id = f"{DOMAIN}.hdmi_{hex(self._logical_address)[2:]}"
def send_keypress(self, key):
"""Send keypress to CEC adapter."""
+1 -3
View File
@@ -28,9 +28,7 @@ class CecSwitchDevice(CecDevice, SwitchDevice):
def __init__(self, device, logical) -> None:
"""Initialize the HDMI device."""
CecDevice.__init__(self, device, logical)
self.entity_id = "{}.{}_{}".format(
DOMAIN, "hdmi", hex(self._logical_address)[2:]
)
self.entity_id = f"{DOMAIN}.hdmi_{hex(self._logical_address)[2:]}"
def turn_on(self, **kwargs) -> None:
"""Turn device on."""
+4 -6
View File
@@ -71,7 +71,7 @@ class N26Account(Entity):
@property
def name(self) -> str:
"""Friendly name of the sensor."""
return "n26_{}".format(self._iban[-4:])
return f"n26_{self._iban[-4:]}"
@property
def state(self) -> float:
@@ -110,7 +110,7 @@ class N26Account(Entity):
}
for limit in self._data.limits:
limit_attr_name = "limit_{}".format(limit["limit"].lower())
limit_attr_name = f"limit_{limit['limit'].lower()}"
attributes[limit_attr_name] = limit["amount"]
return attributes
@@ -143,7 +143,7 @@ class N26Card(Entity):
@property
def name(self) -> str:
"""Friendly name of the sensor."""
return "{}_card_{}".format(self._account_name.lower(), self._card["id"])
return f"{self._account_name.lower()}_card_{self._card['id']}"
@property
def state(self) -> float:
@@ -206,9 +206,7 @@ class N26Space(Entity):
@property
def unique_id(self):
"""Return the unique ID of the entity."""
return "space_{}_{}".format(
self._data.balance["iban"][-4:], self._space["name"].lower()
)
return f"space_{self._data.balance['iban'][-4:]}_{self._space['name'].lower()}"
@property
def name(self) -> str:
+1 -1
View File
@@ -42,7 +42,7 @@ class N26CardSwitch(SwitchDevice):
@property
def name(self) -> str:
"""Friendly name of the sensor."""
return "card_{}".format(self._card["id"])
return f"card_{self._card['id']}"
@property
def is_on(self):
+3 -7
View File
@@ -200,7 +200,7 @@ async def async_setup_entry(hass, entry):
now = datetime.utcnow()
trip_id = service.data.get(
ATTR_TRIP_ID, "trip_{}".format(int(now.timestamp()))
ATTR_TRIP_ID, f"trip_{int(now.timestamp())}"
)
eta_begin = now + service.data[ATTR_ETA]
eta_window = service.data.get(ATTR_ETA_WINDOW, timedelta(minutes=1))
@@ -368,15 +368,11 @@ class NestSensorDevice(Entity):
if device is not None:
# device specific
self.device = device
self._name = "{} {}".format(
self.device.name_long, self.variable.replace("_", " ")
)
self._name = f"{self.device.name_long} {self.variable.replace('_', ' ')}"
else:
# structure only
self.device = structure
self._name = "{} {}".format(
self.structure.name, self.variable.replace("_", " ")
)
self._name = f"{self.structure.name} {self.variable.replace('_', ' ')}"
self._state = None
self._unit = None
@@ -57,8 +57,8 @@ class AuthPhase:
try:
msg = AUTH_MESSAGE_SCHEMA(msg)
except vol.Invalid as err:
error_msg = "Auth message incorrectly formatted: {}".format(
humanize_error(msg, err)
error_msg = (
f"Auth message incorrectly formatted: {humanize_error(msg, err)}"
)
self._logger.warning(error_msg)
self._send_message(auth_invalid_message(error_msg))
+4 -8
View File
@@ -233,15 +233,13 @@ def _request_app_setup(hass, config):
start_url = f"{hass.config.api.base_url}{WINK_AUTH_CALLBACK_PATH}"
description = """Please create a Wink developer app at
description = f"""Please create a Wink developer app at
https://developer.wink.com.
Add a Redirect URI of {}.
Add a Redirect URI of {start_url}.
They will provide you a Client ID and secret
after reviewing your request.
(This can take several days).
""".format(
start_url
)
"""
hass.data[DOMAIN]["configuring"][DOMAIN] = configurator.request_config(
DOMAIN,
@@ -351,9 +349,7 @@ def setup(hass, config):
# Home .
else:
redirect_uri = "{}{}".format(
hass.config.api.base_url, WINK_AUTH_CALLBACK_PATH
)
redirect_uri = f"{hass.config.api.base_url}{WINK_AUTH_CALLBACK_PATH}"
wink_auth_start_url = pywink.get_authorization_url(
config_file.get(ATTR_CLIENT_ID), redirect_uri
@@ -58,8 +58,8 @@ class WirelessTagSensor(WirelessTagBaseSensor):
# sensor.wirelesstag_bedroom_temperature
# and not as sensor.bedroom for temperature and
# sensor.bedroom_2 for humidity
self._entity_id = "{}.{}_{}_{}".format(
"sensor", WIRELESSTAG_DOMAIN, self.underscored_name, self._sensor_type
self._entity_id = (
f"sensor.{WIRELESSTAG_DOMAIN}_{self.underscored_name}_{self._sensor_type}"
)
async def async_added_to_hass(self):
@@ -57,7 +57,7 @@ class WirelessTagSwitch(WirelessTagBaseSensor, SwitchDevice):
super().__init__(api, tag)
self._switch_type = switch_type
self.sensor_type = SWITCH_TYPES[self._switch_type][1]
self._name = "{} {}".format(self._tag.name, SWITCH_TYPES[self._switch_type][0])
self._name = f"{self._tag.name} {SWITCH_TYPES[self._switch_type][0]}"
def turn_on(self, **kwargs):
"""Turn on the switch."""
+3 -2
View File
@@ -320,8 +320,9 @@ class WithingsHealthSensor(Entity):
@property
def unique_id(self) -> str:
"""Return a unique, Home Assistant friendly identifier for this entity."""
return "withings_{}_{}_{}".format(
self._slug, self._user_id, slugify(self._attribute.measurement)
return (
f"withings_{self._slug}_{self._user_id}_"
f"{slugify(self._attribute.measurement)}"
)
@property
+15 -11
View File
@@ -217,9 +217,9 @@ class WUHourlyForecastSensorConfig(WUSensorConfig):
:param field: field name to use as value
"""
super().__init__(
friendly_name=lambda wu: "{} {}".format(
wu.data["hourly_forecast"][period]["FCTTIME"]["weekday_name_abbrev"],
wu.data["hourly_forecast"][period]["FCTTIME"]["civil"],
friendly_name=lambda wu: (
f"{wu.data['hourly_forecast'][period]['FCTTIME']['weekday_name_abbrev']} "
f"{wu.data['hourly_forecast'][period]['FCTTIME']['civil']}"
),
feature="hourly",
value=lambda wu: wu.data["hourly_forecast"][period][field],
@@ -477,8 +477,9 @@ SENSOR_TYPES = {
"Wind Summary", "wind_string", "mdi:weather-windy"
),
"temp_high_record_c": WUAlmanacSensorConfig(
lambda wu: "High Temperature Record ({})".format(
wu.data["almanac"]["temp_high"]["recordyear"]
lambda wu: (
f"High Temperature Record "
f"({wu.data['almanac']['temp_high']['recordyear']})"
),
"temp_high",
"record",
@@ -487,8 +488,9 @@ SENSOR_TYPES = {
"mdi:thermometer",
),
"temp_high_record_f": WUAlmanacSensorConfig(
lambda wu: "High Temperature Record ({})".format(
wu.data["almanac"]["temp_high"]["recordyear"]
lambda wu: (
f"High Temperature Record "
f"({wu.data['almanac']['temp_high']['recordyear']})"
),
"temp_high",
"record",
@@ -497,8 +499,9 @@ SENSOR_TYPES = {
"mdi:thermometer",
),
"temp_low_record_c": WUAlmanacSensorConfig(
lambda wu: "Low Temperature Record ({})".format(
wu.data["almanac"]["temp_low"]["recordyear"]
lambda wu: (
f"Low Temperature Record "
f"({wu.data['almanac']['temp_low']['recordyear']})"
),
"temp_low",
"record",
@@ -507,8 +510,9 @@ SENSOR_TYPES = {
"mdi:thermometer",
),
"temp_low_record_f": WUAlmanacSensorConfig(
lambda wu: "Low Temperature Record ({})".format(
wu.data["almanac"]["temp_low"]["recordyear"]
lambda wu: (
f"Low Temperature Record "
f"({wu.data['almanac']['temp_low']['recordyear']})"
),
"temp_low",
"record",
+1 -3
View File
@@ -136,9 +136,7 @@ class XiaomiCamera(Camera):
else:
video = videos[-1]
return "ftp://{}:{}@{}:{}{}/{}".format(
self.user, self.passwd, host, self.port, ftp.pwd(), video
)
return f"ftp://{self.user}:{self.passwd}@{host}:{self.port}{ftp.pwd()}/{video}"
async def async_camera_image(self):
"""Return a still image response from the camera."""
@@ -242,8 +242,8 @@ class XiaomiDevice(Entity):
self.parse_voltage(device["data"])
if hasattr(self, "_data_key") and self._data_key: # pylint: disable=no-member
self._unique_id = "{}{}".format(
self._data_key, self._sid # pylint: disable=no-member
self._unique_id = (
f"{self._data_key}{self._sid}" # pylint: disable=no-member
)
else:
self._unique_id = f"{self._type}{self._sid}"
@@ -718,7 +718,7 @@ class XiaomiPhilipsEyecareLampAmbientLight(XiaomiPhilipsAbstractLight):
"""Initialize the light device."""
name = f"{name} Ambient Light"
if unique_id is not None:
unique_id = "{}-{}".format(unique_id, "ambient")
unique_id = f"{unique_id}-ambient"
super().__init__(name, light, model, unique_id)
async def async_turn_on(self, **kwargs):
@@ -429,7 +429,7 @@ class ChuangMiPlugSwitch(XiaomiPlugGenericSwitch):
name = f"{name} USB" if channel_usb else name
if unique_id is not None and channel_usb:
unique_id = "{}-{}".format(unique_id, "usb")
unique_id = f"{unique_id}-usb"
super().__init__(name, plug, model, unique_id)
self._channel_usb = channel_usb
+3 -8
View File
@@ -110,14 +110,9 @@ class YiCamera(Camera):
await ftp.quit()
self._is_on = True
return "ftp://{}:{}@{}:{}{}/{}/{}".format(
self.user,
self.passwd,
self.host,
self.port,
self.path,
latest_dir,
videos[-1],
return (
f"ftp://{self.user}:{self.passwd}@{self.host}:"
f"{self.port}{self.path}/{latest_dir}/{videos[-1]}"
)
except (ConnectionRefusedError, StatusCodeError) as err:
_LOGGER.error("Error while fetching video: %s", err)
+1 -1
View File
@@ -159,7 +159,7 @@ class ZamgData:
"""The class for handling the data retrieval."""
API_URL = "http://www.zamg.ac.at/ogd/"
API_HEADERS = {USER_AGENT: "{} {}".format("home-assistant.zamg/", __version__)}
API_HEADERS = {USER_AGENT: f"home-assistant.zamg/ {__version__}"}
def __init__(self, station_id):
"""Initialize the probe."""
+3 -2
View File
@@ -78,8 +78,9 @@ class ZamgWeather(WeatherEntity):
@property
def name(self):
"""Return the name of the sensor."""
return self.stationname or "ZAMG {}".format(
self.zamg_data.data.get("Name") or "(unknown station)"
return (
self.stationname
or f"ZAMG {self.zamg_data.data.get('Name') or '(unknown station)'}"
)
@property
+6 -9
View File
@@ -93,9 +93,7 @@ class ZHADevice(LogMixin):
self._zigpy_device = zigpy_device
self._zha_gateway = zha_gateway
self._available = False
self._available_signal = "{}_{}_{}".format(
self.name, self.ieee, SIGNAL_AVAILABLE
)
self._available_signal = f"{self.name}_{self.ieee}_{SIGNAL_AVAILABLE}"
self._checkins_missed_count = 0
self.unsubs = []
self.unsubs.append(
@@ -104,10 +102,11 @@ class ZHADevice(LogMixin):
)
)
self.quirk_applied = isinstance(self._zigpy_device, zigpy.quirks.CustomDevice)
self.quirk_class = "{}.{}".format(
self._zigpy_device.__class__.__module__,
self._zigpy_device.__class__.__name__,
self.quirk_class = (
f"{self._zigpy_device.__class__.__module__}."
f"{self._zigpy_device.__class__.__name__}"
)
if self.is_mains_powered:
self._consider_unavailable_time = _CONSIDER_UNAVAILABLE_MAINS
else:
@@ -352,9 +351,7 @@ class ZHADevice(LogMixin):
if self._available != available and available:
# Update the state the first time the device comes online
async_dispatcher_send(self.hass, self._available_signal, False)
async_dispatcher_send(
self.hass, "{}_{}".format(self._available_signal, "entity"), available
)
async_dispatcher_send(self.hass, f"{self._available_signal}_entity", available)
self._available = available
@property
+2 -2
View File
@@ -119,7 +119,7 @@ class BaseZhaEntity(RestoreEntity, LogMixin, entity.Entity):
self.remove_future = asyncio.Future()
await self.async_accept_signal(
None,
"{}_{}".format(SIGNAL_REMOVE, str(self.zha_device.ieee)),
f"{SIGNAL_REMOVE}_{self.zha_device.ieee}",
self.async_remove,
signal_override=True,
)
@@ -182,7 +182,7 @@ class ZhaEntity(BaseZhaEntity):
await self.async_check_recently_seen()
await self.async_accept_signal(
None,
"{}_{}".format(self.zha_device.available_signal, "entity"),
f"{self.zha_device.available_signal}_entity",
self.async_set_available,
signal_override=True,
)
+2 -4
View File
@@ -261,7 +261,7 @@ def _obj_to_dict(obj):
def _value_name(value):
"""Return the name of the value."""
return "{} {}".format(node_name(value.node), value.label).strip()
return f"{node_name(value.node)} {value.label}".strip()
def nice_print_node(node):
@@ -826,9 +826,7 @@ async def async_setup_entry(hass, config_entry):
)
return
_LOGGER.info(
"Node %s on instance %s does not have resettable meters.",
node_id,
instance,
"Node %s on instance %s does not have resettable meters.", node_id, instance
)
def heal_node(service):
+8 -9
View File
@@ -337,21 +337,20 @@ class ZwaveLock(ZWaveDeviceEntity, LockDevice):
)
if alarm_type == 21:
self._lock_status = "{}{}".format(
LOCK_ALARM_TYPE.get(str(alarm_type)),
MANUAL_LOCK_ALARM_LEVEL.get(str(alarm_level)),
self._lock_status = (
f"{LOCK_ALARM_TYPE.get(str(alarm_type))}"
f"{MANUAL_LOCK_ALARM_LEVEL.get(str(alarm_level))}"
)
return
if str(alarm_type) in ALARM_TYPE_STD:
self._lock_status = "{}{}".format(
LOCK_ALARM_TYPE.get(str(alarm_type)), str(alarm_level)
)
self._lock_status = f"{LOCK_ALARM_TYPE.get(str(alarm_type))}{alarm_level}"
return
if alarm_type == 161:
self._lock_status = "{}{}".format(
LOCK_ALARM_TYPE.get(str(alarm_type)),
TAMPER_ALARM_LEVEL.get(str(alarm_level)),
self._lock_status = (
f"{LOCK_ALARM_TYPE.get(str(alarm_type))}"
f"{TAMPER_ALARM_LEVEL.get(str(alarm_level))}"
)
return
if alarm_type != 0:
self._lock_status = LOCK_ALARM_TYPE.get(str(alarm_type))