Various string cleanups (#30435)

* Remove some unnecessary string concatenations

* Replace some simple str.formats with f-strings

* Replace some string concatenations with f-strings
This commit is contained in:
Ville Skyttä authored and Paulus Schoutsen committed 2020-01-03 14:47:06 +01:00
1 parent 5ad209c6fd
commit fa4fa30461
105 files changed
+241 -314

No files matched your search

+1 -1
View File
@@ -36,5 +36,5 @@ def extract_domain_configs(config: ConfigType, domain: str) -> Sequence[str]:
Async friendly.
"""
pattern = re.compile(r"^{}(| .+)$".format(domain))
pattern = re.compile(fr"^{domain}(| .+)$")
return [key for key in config.keys() if pattern.match(key)]
+1 -3
View File
@@ -69,9 +69,7 @@ async def async_check_ha_config_file(hass: HomeAssistant) -> HomeAssistantConfig
package: str, component: str, config: ConfigType, message: str
) -> None:
"""Handle errors from packages: _log_pkg_error."""
message = "Package {} setup failed. Component {} {}".format(
package, component, message
)
message = f"Package {package} setup failed. Component {component} {message}"
domain = f"homeassistant.packages.{package}.{component}"
pack_config = core_config[CONF_PACKAGES].get(package, config)
result.add_error(message, domain, pack_config)
+19 -23
View File
@@ -135,7 +135,7 @@ def boolean(value: Any) -> bool:
elif isinstance(value, Number):
# type ignore: https://github.com/python/mypy/issues/3186
return value != 0 # type: ignore
raise vol.Invalid("invalid boolean value {}".format(value))
raise vol.Invalid(f"invalid boolean value {value}")
def isdevice(value: Any) -> str:
@@ -144,7 +144,7 @@ def isdevice(value: Any) -> str:
os.stat(value)
return str(value)
except OSError:
raise vol.Invalid("No device at {} found".format(value))
raise vol.Invalid(f"No device at {value} found")
def matches_regex(regex: str) -> Callable[[Any], str]:
@@ -154,13 +154,11 @@ def matches_regex(regex: str) -> Callable[[Any], str]:
def validator(value: Any) -> str:
"""Validate that value matches the given regex."""
if not isinstance(value, str):
raise vol.Invalid("not a string value: {}".format(value))
raise vol.Invalid(f"not a string value: {value}")
if not compiled.match(value):
raise vol.Invalid(
"value {} does not match regular expression {}".format(
value, compiled.pattern
)
f"value {value} does not match regular expression {compiled.pattern}"
)
return value
@@ -175,10 +173,10 @@ def is_regex(value: Any) -> Pattern[Any]:
return r
except TypeError:
raise vol.Invalid(
"value {} is of the wrong type for a regular expression".format(value)
f"value {value} is of the wrong type for a regular expression"
)
except re.error:
raise vol.Invalid("value {} is not a valid regular expression".format(value))
raise vol.Invalid(f"value {value} is not a valid regular expression")
def isfile(value: Any) -> str:
@@ -220,7 +218,7 @@ def entity_id(value: Any) -> str:
if valid_entity_id(str_value):
return str_value
raise vol.Invalid("Entity ID {} is an invalid entity id".format(value))
raise vol.Invalid(f"Entity ID {value} is an invalid entity id")
def entity_ids(value: Union[str, List]) -> List[str]:
@@ -256,9 +254,7 @@ def entities_domain(domain: str) -> Callable[[Union[str, List]], List[str]]:
for ent_id in values:
if split_entity_id(ent_id)[0] != domain:
raise vol.Invalid(
"Entity ID '{}' does not belong to domain '{}'".format(
ent_id, domain
)
f"Entity ID '{ent_id}' does not belong to domain '{domain}'"
)
return values
@@ -307,7 +303,7 @@ def time(value: Any) -> time_sys:
raise vol.Invalid("Not a parseable type")
if time_val is None:
raise vol.Invalid("Invalid time specified: {}".format(value))
raise vol.Invalid(f"Invalid time specified: {value}")
return time_val
@@ -368,7 +364,7 @@ def time_period_seconds(value: Union[int, str]) -> timedelta:
try:
return timedelta(seconds=int(value))
except (ValueError, TypeError):
raise vol.Invalid("Expected seconds, got {}".format(value))
raise vol.Invalid(f"Expected seconds, got {value}")
time_period = vol.Any(time_period_str, time_period_seconds, timedelta, time_period_dict)
@@ -400,7 +396,7 @@ def service(value: Any) -> str:
str_value = string(value).lower()
if valid_entity_id(str_value):
return str_value
raise vol.Invalid("Service {} does not match format <domain>.<name>".format(value))
raise vol.Invalid(f"Service {value} does not match format <domain>.<name>")
def schema_with_slug_keys(value_schema: Union[T, Callable]) -> Callable:
@@ -432,7 +428,7 @@ def slug(value: Any) -> str:
slg = util_slugify(str_value)
if str_value == slg:
return str_value
raise vol.Invalid("invalid slug {} (try {})".format(value, slg))
raise vol.Invalid(f"invalid slug {value} (try {slg})")
def slugify(value: Any) -> str:
@@ -442,7 +438,7 @@ def slugify(value: Any) -> str:
slg = util_slugify(str(value))
if slg:
return slg
raise vol.Invalid("Unable to slugify {}".format(value))
raise vol.Invalid(f"Unable to slugify {value}")
def string(value: Any) -> str:
@@ -484,7 +480,7 @@ def template(value: Optional[Any]) -> template_helper.Template:
template_value.ensure_valid()
return cast(template_helper.Template, template_value)
except TemplateError as ex:
raise vol.Invalid("invalid template ({})".format(ex))
raise vol.Invalid(f"invalid template ({ex})")
def template_complex(value: Any) -> Any:
@@ -515,7 +511,7 @@ def datetime(value: Any) -> datetime_sys:
date_val = None
if date_val is None:
raise vol.Invalid("Invalid datetime specified: {}".format(value))
raise vol.Invalid(f"Invalid datetime specified: {value}")
return date_val
@@ -545,8 +541,8 @@ def socket_timeout(value: Optional[Any]) -> object:
if float_value > 0.0:
return float_value
raise vol.Invalid("Invalid socket timeout value. float > 0.0 required.")
except Exception as _:
raise vol.Invalid("Invalid socket timeout: {err}".format(err=_))
except Exception as err:
raise vol.Invalid(f"Invalid socket timeout: {err}")
# pylint: disable=no-value-for-parameter
@@ -700,8 +696,8 @@ def key_dependency(
raise vol.Invalid("key dependencies require a dict")
if key in value and dependency not in value:
raise vol.Invalid(
'dependency violation - key "{}" requires '
'key "{}" to exist'.format(key, dependency)
f'dependency violation - key "{key}" requires '
f'key "{dependency}" to exist'
)
return value
+2 -2
View File
@@ -65,7 +65,7 @@ def discover(hass, service, discovered, component, hass_config):
async def async_discover(hass, service, discovered, component, hass_config):
"""Fire discovery event. Can ensure a component is loaded."""
if component in DEPENDENCY_BLACKLIST:
raise HomeAssistantError("Cannot discover the {} component.".format(component))
raise HomeAssistantError(f"Cannot discover the {component} component.")
if component is not None and component not in hass.config.components:
await setup.async_setup_component(hass, component, hass_config)
@@ -151,7 +151,7 @@ async def async_load_platform(hass, component, platform, discovered, hass_config
assert hass_config, "You need to pass in the real hass config"
if component in DEPENDENCY_BLACKLIST:
raise HomeAssistantError("Cannot discover the {} component.".format(component))
raise HomeAssistantError(f"Cannot discover the {component} component.")
setup_success = True
+1 -1
View File
@@ -562,7 +562,7 @@ class Entity(ABC):
def __repr__(self) -> str:
"""Return the representation."""
return "<Entity {}: {}>".format(self.name, self.state)
return f"<Entity {self.name}: {self.state}>"
# call an requests
async def async_request_call(self, coro):
+3 -9
View File
@@ -304,9 +304,7 @@ class EntityPlatform:
suggested_object_id = entity.name
if self.entity_namespace is not None:
suggested_object_id = "{} {}".format(
self.entity_namespace, suggested_object_id
)
suggested_object_id = f"{self.entity_namespace} {suggested_object_id}"
if self.config_entry is not None:
config_entry_id = self.config_entry.entry_id
@@ -380,9 +378,7 @@ class EntityPlatform:
)
if self.entity_namespace is not None:
suggested_object_id = "{} {}".format(
self.entity_namespace, suggested_object_id
)
suggested_object_id = f"{self.entity_namespace} {suggested_object_id}"
entity.entity_id = entity_registry.async_generate_entity_id(
self.domain, suggested_object_id, self.entities.keys()
)
@@ -402,9 +398,7 @@ class EntityPlatform:
if already_exists:
msg = f"Entity id already exists: {entity.entity_id}"
if entity.unique_id is not None:
msg += ". Platform {} does not generate unique IDs".format(
self.platform_name
)
msg += f". Platform {self.platform_name} does not generate unique IDs"
raise HomeAssistantError(msg)
entity_id = entity.entity_id
+2 -3
View File
@@ -323,9 +323,8 @@ class EntityRegistry:
)
if conflict:
raise ValueError(
"Unique id '{}' is already in use by '{}'".format(
new_unique_id, conflict.entity_id
)
f"Unique id '{new_unique_id}' is already in use by "
f"'{conflict.entity_id}'"
)
changes["unique_id"] = new_unique_id
+1 -1
View File
@@ -8,7 +8,7 @@ def icon_for_battery_level(
"""Return a battery icon valid identifier."""
icon = "mdi:battery"
if battery_level is None:
return icon + "-unknown"
return f"{icon}-unknown"
if charging and battery_level > 10:
icon += "-charging-{}".format(int(round(battery_level / 20 - 0.01)) * 20)
elif charging:
+1 -1
View File
@@ -158,7 +158,7 @@ class IntentHandler:
def __repr__(self) -> str:
"""Represent a string of an intent handler."""
return "<{} - {}>".format(self.__class__.__name__, self.intent_type)
return f"<{self.__class__.__name__} - {self.intent_type}>"
def _fuzzymatch(name: str, items: Iterable[T], key: Callable[[T], str]) -> Optional[T]:
+3 -3
View File
@@ -299,7 +299,7 @@ class Script:
_LOGGER.error("Error rendering '%s' delay template: %s", self.name, ex)
raise _StopScript
self.last_action = action.get(CONF_ALIAS, "delay {}".format(delay))
self.last_action = action.get(CONF_ALIAS, f"delay {delay}")
self._log("Executing step %s" % self.last_action)
unsub = async_track_point_in_utc_time(
@@ -408,7 +408,7 @@ class Script:
self.last_action = action.get(CONF_ALIAS, action[CONF_CONDITION])
check = config(self.hass, variables)
self._log("Test condition {}: {}".format(self.last_action, check))
self._log(f"Test condition {self.last_action}: {check}")
if not check:
raise _StopScript
@@ -446,6 +446,6 @@ class Script:
def _log(self, msg):
"""Logger helper."""
if self.name is not None:
msg = "Script {}: {}".format(self.name, msg)
msg = f"Script {self.name}: {msg}"
_LOGGER.info(msg)
+1 -1
View File
@@ -240,7 +240,7 @@ def async_set_service_schema(hass, domain, service, schema):
"fields": schema.get("fields") or {},
}
hass.data[SERVICE_DESCRIPTION_CACHE]["{}.{}".format(domain, service)] = description
hass.data[SERVICE_DESCRIPTION_CACHE][f"{domain}.{service}"] = description
@bind_hass
+2 -2
View File
@@ -328,7 +328,7 @@ class AllStates:
if not valid_entity_id(name):
raise TemplateError(f"Invalid entity ID '{name}'")
return _get_state(self._hass, name)
if not valid_entity_id(name + ".entity"):
if not valid_entity_id(f"{name}.entity"):
raise TemplateError(f"Invalid domain name '{name}'")
return DomainStates(self._hass, name)
@@ -451,7 +451,7 @@ class TemplateState(State):
"""Representation of Template State."""
state = object.__getattribute__(self, "_access_state")()
rep = state.__repr__()
return "<template " + rep[1:]
return f"<template {rep[1:]}"
def _collect_state(hass, entity_id):
+1 -1
View File
@@ -53,7 +53,7 @@ async def component_translation_file(
assert integration is not None, domain
if is_platform:
filename = "{}.{}.json".format(parts[0], language)
filename = f"{parts[0]}.{language}.json"
return str(integration.file_path / ".translations" / filename)
# If it's a component that is just one file, we don't support translations