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: with BytesIO() as buffer:
qr_code.svg(file=buffer, scale=4) qr_code.svg(file=buffer, scale=4)
return "{}".format( return str(
buffer.getvalue() buffer.getvalue()
.decode("ascii") .decode("ascii")
.replace("\n", "") .replace("\n", "")

View File

@ -74,8 +74,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
try: try:
bridge = Lightify(host, log_level=logging.NOTSET) bridge = Lightify(host, log_level=logging.NOTSET)
except OSError as err: except OSError as err:
msg = "Error connecting to bridge: {} due to: {}".format(host, str(err)) _LOGGER.exception("Error connecting to bridge: %s due to: %s", host, err)
_LOGGER.exception(msg)
return return
setup_bridge(bridge, add_entities, config) setup_bridge(bridge, add_entities, config)
@ -380,9 +379,7 @@ class OsramLightifyLight(Luminary):
"""Update static attributes of the luminary.""" """Update static attributes of the luminary."""
super().update_static_attributes() super().update_static_attributes()
attrs = { attrs = {
"device_type": "{} ({})".format( "device_type": f"{self._luminary.type_id()} ({self._luminary.devicename()})",
self._luminary.type_id(), self._luminary.devicename()
),
"firmware_version": self._luminary.version(), "firmware_version": self._luminary.version(),
} }
if self._luminary.devicetype().name == "SENSOR": 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): async def _async_transition_message_enter(hass, context, message, location):
"""Execute enter event.""" """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) dev_id, kwargs = _parse_see_args(message, context.mqtt_topic)
if zone is None and message.get("t") == "b": 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 new_region = regions[-1] if regions else None
if new_region: if new_region:
# Exit to previous 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) _set_gps_from_zone(kwargs, new_region, zone)
_LOGGER.info("Exit to %s", new_region) _LOGGER.info("Exit to %s", new_region)
context.async_see(**kwargs) context.async_see(**kwargs)

View File

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

View File

@ -127,4 +127,4 @@ async def handle_webhook(hass, webhook_id, request):
def _device_id(data): def _device_id(data):
"""Return name of device sensor.""" """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"])}, "connections": {("mac", device["device_mac"])},
"identifieres": device["device_id"], "identifieres": device["device_id"],
"manufacturer": "Minut", "manufacturer": "Minut",
"model": "Point v{}".format(device["hardware_version"]), "model": f"Point v{device['hardware_version']}",
"name": device["description"], "name": device["description"],
"sw_version": device["firmware"]["installed"], "sw_version": device["firmware"]["installed"],
"via_device": (DOMAIN, device["home"]), "via_device": (DOMAIN, device["home"]),

View File

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

View File

@ -61,7 +61,7 @@ def setup_proximity_component(hass, name, config):
unit_of_measurement = config.get( unit_of_measurement = config.get(
CONF_UNIT_OF_MEASUREMENT, hass.config.units.length_unit 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( proximity = Proximity(
hass, hass,

View File

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

View File

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

View File

@ -352,7 +352,7 @@ class PS4Device(MediaPlayerDevice):
else: else:
_sw_version = status["system-version"] _sw_version = status["system-version"]
_sw_version = _sw_version[1:4] _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 = { self._info = {
"name": status["host-name"], "name": status["host-name"],
"model": "PlayStation 4", "model": "PlayStation 4",

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -107,9 +107,7 @@ def setup(hass, config):
except (ConnectTimeout, HTTPError) as ex: except (ConnectTimeout, HTTPError) as ex:
_LOGGER.error("Unable to connect to Rain Cloud service: %s", str(ex)) _LOGGER.error("Unable to connect to Rain Cloud service: %s", str(ex))
hass.components.persistent_notification.create( hass.components.persistent_notification.create(
"Error: {}<br />" f"Error: {ex}<br />" "You will need to restart hass after fixing.",
"You will need to restart hass after fixing."
"".format(ex),
title=NOTIFICATION_TITLE, title=NOTIFICATION_TITLE,
notification_id=NOTIFICATION_ID, notification_id=NOTIFICATION_ID,
) )
@ -142,7 +140,7 @@ class RainCloudEntity(Entity):
"""Initialize the RainCloud entity.""" """Initialize the RainCloud entity."""
self.data = data self.data = data
self._sensor_type = sensor_type 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 self._state = None
@property @property

View File

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

View File

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

View File

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