Improve string formatting v9 (#34050)

* Improve string formatting v9

* Address review comments
This commit is contained in:
springstan 2020-04-12 17:18:09 +02:00 committed by GitHub
parent 5aca16ef01
commit b2af1de273
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 47 additions and 72 deletions

View File

@ -41,7 +41,7 @@ def _generate_qr_code(data: str) -> str:
with BytesIO() as buffer:
qr_code.svg(file=buffer, scale=4)
return "{}".format(
return str(
buffer.getvalue()
.decode("ascii")
.replace("\n", "")

View File

@ -74,8 +74,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
try:
bridge = Lightify(host, log_level=logging.NOTSET)
except OSError as err:
msg = "Error connecting to bridge: {} due to: {}".format(host, str(err))
_LOGGER.exception(msg)
_LOGGER.exception("Error connecting to bridge: %s due to: %s", host, err)
return
setup_bridge(bridge, add_entities, config)
@ -380,9 +379,7 @@ class OsramLightifyLight(Luminary):
"""Update static attributes of the luminary."""
super().update_static_attributes()
attrs = {
"device_type": "{} ({})".format(
self._luminary.type_id(), self._luminary.devicename()
),
"device_type": f"{self._luminary.type_id()} ({self._luminary.devicename()})",
"firmware_version": self._luminary.version(),
}
if self._luminary.devicetype().name == "SENSOR":

View File

@ -199,7 +199,7 @@ async def async_handle_location_message(hass, context, message):
async def _async_transition_message_enter(hass, context, message, location):
"""Execute enter event."""
zone = hass.states.get("zone.{}".format(slugify(location)))
zone = hass.states.get(f"zone.{slugify(location)}")
dev_id, kwargs = _parse_see_args(message, context.mqtt_topic)
if zone is None and message.get("t") == "b":
@ -240,7 +240,7 @@ async def _async_transition_message_leave(hass, context, message, location):
new_region = regions[-1] if regions else None
if new_region:
# Exit to previous region
zone = hass.states.get("zone.{}".format(slugify(new_region)))
zone = hass.states.get(f"zone.{slugify(new_region)}")
_set_gps_from_zone(kwargs, new_region, zone)
_LOGGER.info("Exit to %s", new_region)
context.async_see(**kwargs)

View File

@ -45,12 +45,10 @@ def ensure_unique_names_and_slugs(config):
slugs[conf[CONF_SLUG]] = conf[CONF_HOST]
else:
raise vol.Invalid(
"Duplicate name '{}' (or slug '{}') for '{}' (already in use by '{}'). Each configured Pi-hole must have a unique name.".format(
conf[CONF_NAME],
conf[CONF_SLUG],
conf[CONF_HOST],
names.get(conf[CONF_NAME], slugs[conf[CONF_SLUG]]),
)
f"Duplicate name '{conf[CONF_NAME]}' (or slug '{conf[CONF_SLUG]}') "
f"for '{conf[CONF_HOST]}' (already in use by "
f"'{names.get(conf[CONF_NAME], slugs[conf[CONF_SLUG]])}'). "
"Each configured Pi-hole must have a unique name."
)
return config
@ -108,9 +106,8 @@ async def async_setup(hass, config):
if (data[slug]).api.api_token is None:
raise vol.Invalid(
"Pi-hole '{}' must have an api_key provided in configuration to be enabled.".format(
pi_hole.name
)
f"Pi-hole '{pi_hole.name}' must have an api_key "
"provided in configuration to be enabled."
)
return call_data
@ -122,7 +119,7 @@ async def async_setup(hass, config):
cv.time_period_str, cv.positive_timedelta
),
vol.Optional(SERVICE_DISABLE_ATTR_NAME): vol.In(
[conf[CONF_NAME] for conf in config[DOMAIN]], msg="Unknown Pi-Hole",
[conf[CONF_NAME] for conf in config[DOMAIN]], msg="Unknown Pi-Hole"
),
},
ensure_api_token,

View File

@ -127,4 +127,4 @@ async def handle_webhook(hass, webhook_id, request):
def _device_id(data):
"""Return name of device sensor."""
return "{}_{}".format(data.get(ATTR_DEVICE_NAME), data.get(ATTR_DEVICE_ID))
return f"{data.get(ATTR_DEVICE_NAME)}_{data.get(ATTR_DEVICE_ID)}"

View File

@ -309,7 +309,7 @@ class MinutPointEntity(Entity):
"connections": {("mac", device["device_mac"])},
"identifieres": device["device_id"],
"manufacturer": "Minut",
"model": "Point v{}".format(device["hardware_version"]),
"model": f"Point v{device['hardware_version']}",
"name": device["description"],
"sw_version": device["firmware"]["installed"],
"via_device": (DOMAIN, device["home"]),

View File

@ -39,7 +39,7 @@ class ProwlNotificationService(BaseNotificationService):
"""Send the message to the user."""
response = None
session = None
url = "{}{}".format(_RESOURCE, "add")
url = f"{_RESOURCE}add"
data = kwargs.get(ATTR_DATA)
payload = {
"apikey": self._api_key,

View File

@ -61,7 +61,7 @@ def setup_proximity_component(hass, name, config):
unit_of_measurement = config.get(
CONF_UNIT_OF_MEASUREMENT, hass.config.units.length_unit
)
zone_id = "zone.{}".format(config.get(CONF_ZONE))
zone_id = f"zone.{config.get(CONF_ZONE)}"
proximity = Proximity(
hass,

View File

@ -188,8 +188,8 @@ class ProxyCamera(Camera):
super().__init__()
self.hass = hass
self._proxied_camera = config.get(CONF_ENTITY_ID)
self._name = config.get(CONF_NAME) or "{} - {}".format(
DEFAULT_BASENAME, self._proxied_camera
self._name = (
config.get(CONF_NAME) or f"{DEFAULT_BASENAME} - {self._proxied_camera}"
)
self._image_opts = ImageOpts(
config.get(CONF_MAX_IMAGE_WIDTH),
@ -258,7 +258,7 @@ class ProxyCamera(Camera):
)
return await async_get_still_stream(
request, self._async_stream_image, self.content_type, self.frame_interval,
request, self._async_stream_image, self.content_type, self.frame_interval
)
@property

View File

@ -139,11 +139,9 @@ async def async_migrate_entry(hass, entry):
config_entries.async_update_entry(entry)
return True
msg = """{} for the PlayStation 4 Integration.
msg = f"""{reason[version]} for the PlayStation 4 Integration.
Please remove the PS4 Integration and re-configure
[here](/config/integrations).""".format(
reason[version]
)
[here](/config/integrations)."""
hass.components.persistent_notification.async_create(
title="PlayStation 4 Integration Configuration Requires Update",

View File

@ -352,7 +352,7 @@ class PS4Device(MediaPlayerDevice):
else:
_sw_version = status["system-version"]
_sw_version = _sw_version[1:4]
sw_version = "{}.{}".format(_sw_version[0], _sw_version[1:])
sw_version = f"{_sw_version[0]}.{_sw_version[1:]}"
self._info = {
"name": status["host-name"],
"model": "PlayStation 4",

View File

@ -77,7 +77,7 @@ class PushBulletNotificationSensor(Entity):
@property
def name(self):
"""Return the name of the sensor."""
return "{} {}".format("Pushbullet", self._element)
return f"Pushbullet {self._element}"
@property
def state(self):

View File

@ -83,7 +83,7 @@ class PyLoadSensor(Entity):
def __init__(self, api, sensor_type, client_name):
"""Initialize a new pyLoad sensor."""
self._name = "{} {}".format(client_name, sensor_type[1])
self._name = f"{client_name} {sensor_type[1]}"
self.type = sensor_type[0]
self.api = api
self._state = None
@ -141,9 +141,7 @@ class PyLoadAPI:
if username is not None and password is not None:
self.payload = {"username": username, "password": password}
self.login = requests.post(
"{}{}".format(api_url, "login"), data=self.payload, timeout=5
)
self.login = requests.post(f"{api_url}login", data=self.payload, timeout=5)
self.update()
def post(self, method, params=None):
@ -155,7 +153,7 @@ class PyLoadAPI:
try:
response = requests.post(
"{}{}".format(self.api_url, "statusServer"),
f"{self.api_url}statusServer",
json=payload,
cookies=self.login.cookies,
headers=self.headers,

View File

@ -177,7 +177,7 @@ class QNAPStatsAPI:
protocol = "https" if config[CONF_SSL] else "http"
self._api = QNAPStats(
"{}://{}".format(protocol, config.get(CONF_HOST)),
f"{protocol}://{config.get(CONF_HOST)}",
config.get(CONF_PORT),
config.get(CONF_USERNAME),
config.get(CONF_PASSWORD),
@ -357,9 +357,7 @@ class QNAPDriveSensor(QNAPSensor):
"""Return the name of the sensor, if any."""
server_name = self._api.data["system_stats"]["system"]["name"]
return "{} {} (Drive {})".format(
server_name, self.var_name, self.monitor_device
)
return f"{server_name} {self.var_name} (Drive {self.monitor_device})"
@property
def device_state_attributes(self):
@ -402,6 +400,4 @@ class QNAPVolumeSensor(QNAPSensor):
data = self._api.data["volumes"][self.monitor_device]
total_gb = int(data["total_size"]) / 1024 / 1024 / 1024
return {
ATTR_VOLUME_SIZE: "{} {}".format(round_nicely(total_gb), DATA_GIBIBYTES)
}
return {ATTR_VOLUME_SIZE: f"{round_nicely(total_gb)} {DATA_GIBIBYTES}"}

View File

@ -34,7 +34,7 @@ class QrEntity(ImageProcessingEntity):
if name:
self._name = name
else:
self._name = "QR {}".format(split_entity_id(camera_entity)[1])
self._name = f"QR {split_entity_id(camera_entity)[1]}"
self._state = None
@property

View File

@ -205,9 +205,7 @@ async def async_setup(hass, config):
# If button pressed, fire a hass event
if QS_ID in qspacket:
if qspacket.get(QS_CMD, "") in cmd_buttons:
hass.bus.async_fire(
"qwikswitch.button.{}".format(qspacket[QS_ID]), qspacket
)
hass.bus.async_fire(f"qwikswitch.button.{qspacket[QS_ID]}", qspacket)
return
if qspacket[QS_ID] in sensor_ids:

View File

@ -106,7 +106,7 @@ class RadarrSensor(Entity):
self.port = conf.get(CONF_PORT)
self.urlbase = conf.get(CONF_URLBASE)
if self.urlbase:
self.urlbase = "{}/".format(self.urlbase.strip("/"))
self.urlbase = f"{self.urlbase.strip('/')}/"
self.apikey = conf.get(CONF_API_KEY)
self.included = conf.get(CONF_INCLUDED)
self.days = int(conf.get(CONF_DAYS))

View File

@ -107,9 +107,7 @@ def setup(hass, config):
except (ConnectTimeout, HTTPError) as ex:
_LOGGER.error("Unable to connect to Rain Cloud 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,
)
@ -142,7 +140,7 @@ class RainCloudEntity(Entity):
"""Initialize the RainCloud entity."""
self.data = data
self._sensor_type = sensor_type
self._name = "{} {}".format(self.data.name, KEY_MAP.get(self._sensor_type))
self._name = f"{self.data.name} {KEY_MAP.get(self._sensor_type)}"
self._state = None
@property

View File

@ -425,9 +425,9 @@ class RainMachineEntity(Entity):
"identifiers": {(DOMAIN, self.rainmachine.controller.mac)},
"name": self.rainmachine.controller.name,
"manufacturer": "RainMachine",
"model": "Version {} (API: {})".format(
self.rainmachine.controller.hardware_version,
self.rainmachine.controller.api_version,
"model": (
f"Version {self.rainmachine.controller.hardware_version} "
f"(API: {self.rainmachine.controller.api_version})"
),
"sw_version": self.rainmachine.controller.software_version,
}

View File

@ -509,11 +509,9 @@ class Event:
"""Return the representation."""
# pylint: disable=maybe-no-member
if self.data:
return "<Event {}[{}]: {}>".format(
self.event_type, str(self.origin)[0], util.repr_helper(self.data)
)
return f"<Event {self.event_type}[{str(self.origin)[0]}]: {util.repr_helper(self.data)}>"
return "<Event {}[{}]>".format(self.event_type, str(self.origin)[0])
return f"<Event {self.event_type}[{str(self.origin)[0]}]>"
def __eq__(self, other: Any) -> bool:
"""Return the comparison."""
@ -826,15 +824,11 @@ class State:
def __repr__(self) -> str:
"""Return the representation of the states."""
attrs = (
"; {}".format(util.repr_helper(self.attributes)) if self.attributes else ""
)
attrs = f"; {util.repr_helper(self.attributes)}" if self.attributes else ""
return "<state {}={}{} @ {}>".format(
self.entity_id,
self.state,
attrs,
dt_util.as_local(self.last_changed).isoformat(),
return (
f"<state {self.entity_id}={self.state}{attrs}"
f" @ {dt_util.as_local(self.last_changed).isoformat()}>"
)
@ -1045,8 +1039,9 @@ class ServiceCall:
def __repr__(self) -> str:
"""Return the representation of the service."""
if self.data:
return "<ServiceCall {}.{} (c:{}): {}>".format(
self.domain, self.service, self.context.id, util.repr_helper(self.data)
return (
f"<ServiceCall {self.domain}.{self.service} "
f"(c:{self.context.id}): {util.repr_helper(self.data)}>"
)
return f"<ServiceCall {self.domain}.{self.service} (c:{self.context.id})>"

View File

@ -419,9 +419,7 @@ def _load_file(
parts = []
for part in path.split("."):
parts.append(part)
white_listed_errors.append(
"No module named '{}'".format(".".join(parts))
)
white_listed_errors.append(f"No module named '{'.'.join(parts)}'")
if str(err) not in white_listed_errors:
_LOGGER.exception(