Use literal string interpolation in core (f-strings) (#26166)

This commit is contained in:
Franck Nijhof authored and Paulus Schoutsen committed 2019-08-23 09:53:33 -07:00
1 parent 1efa29d6ff
commit decf13b948
67 files changed
+180 -246

No files matched your search

+3 -3
View File
@@ -138,7 +138,7 @@ class APIEventStream(HomeAssistantView):
if payload is stop_obj:
break
msg = "data: {}\n\n".format(payload)
msg = f"data: {payload}\n\n"
_LOGGER.debug("STREAM %s WRITING %s", id(stop_obj), msg.strip())
await response.write(msg.encode("UTF-8"))
except asyncio.TimeoutError:
@@ -316,7 +316,7 @@ class APIEventView(HomeAssistantView):
event_type, event_data, ha.EventOrigin.remote, self.context(request)
)
return self.json_message("Event {} fired.".format(event_type))
return self.json_message(f"Event {event_type} fired.")
class APIServicesView(HomeAssistantView):
@@ -388,7 +388,7 @@ class APITemplateView(HomeAssistantView):
return tpl.async_render(data.get("variables"))
except (ValueError, TemplateError) as ex:
return self.json_message(
"Error rendering template: {}".format(ex), HTTP_BAD_REQUEST
f"Error rendering template: {ex}", HTTP_BAD_REQUEST
)
@@ -143,7 +143,7 @@ async def async_setup(hass, config):
async def turn_onoff_service_handler(service_call):
"""Handle automation turn on/off service calls."""
tasks = []
method = "async_{}".format(service_call.service)
method = f"async_{service_call.service}"
for entity in await component.async_extract_from_service(service_call):
tasks.append(getattr(entity, method)())
@@ -378,7 +378,7 @@ async def _async_process_config(hass, config, component):
for list_no, config_block in enumerate(conf):
automation_id = config_block.get(CONF_ID)
name = config_block.get(CONF_ALIAS) or "{} {}".format(config_key, list_no)
name = config_block.get(CONF_ALIAS) or f"{config_key} {list_no}"
hidden = config_block[CONF_HIDE_ENTITY]
initial_state = config_block.get(CONF_INITIAL_STATE)
@@ -431,7 +431,7 @@ def _async_get_action(hass, config, name):
await script_obj.async_run(variables, context)
except Exception as err: # pylint: disable=broad-except
script_obj.async_log_exception(
_LOGGER, "Error while executing automation {}".format(entity_id), err
_LOGGER, f"Error while executing automation {entity_id}", err
)
return action
+6 -6
View File
@@ -36,7 +36,7 @@ async def async_setup(hass, config):
async def setup_panel(panel_name):
"""Set up a panel."""
panel = importlib.import_module(".{}".format(panel_name), __name__)
panel = importlib.import_module(f".{panel_name}", __name__)
if not panel:
return
@@ -44,7 +44,7 @@ async def async_setup(hass, config):
success = await panel.async_setup(hass)
if success:
key = "{}.{}".format(DOMAIN, panel_name)
key = f"{DOMAIN}.{panel_name}"
hass.bus.async_fire(EVENT_COMPONENT_LOADED, {ATTR_COMPONENT: key})
@callback
@@ -82,8 +82,8 @@ class BaseEditConfigView(HomeAssistantView):
post_write_hook=None,
):
"""Initialize a config view."""
self.url = "/api/config/%s/%s/{config_key}" % (component, config_type)
self.name = "api:config:%s:%s" % (component, config_type)
self.url = f"/api/config/{component}/{config_type}/{{config_key}}"
self.name = f"api:config:{component}:{config_type}"
self.path = path
self.key_schema = key_schema
self.data_schema = data_schema
@@ -126,14 +126,14 @@ class BaseEditConfigView(HomeAssistantView):
try:
self.key_schema(config_key)
except vol.Invalid as err:
return self.json_message("Key malformed: {}".format(err), 400)
return self.json_message(f"Key malformed: {err}", 400)
try:
# We just validate, we don't store that data because
# we don't want to store the defaults.
self.data_schema(data)
except vol.Invalid as err:
return self.json_message("Message malformed: {}".format(err), 400)
return self.json_message(f"Message malformed: {err}", 400)
hass = request.app["hass"]
path = hass.config.path(self.path)
@@ -61,10 +61,10 @@ def async_request_config(
Will return an ID to be used for sequent calls.
"""
if link_name is not None and link_url is not None:
description += "\n\n[{}]({})".format(link_name, link_url)
description += f"\n\n[{link_name}]({link_url})"
if description_image is not None:
description += "\n\n![Description image]({})".format(description_image)
description += f"\n\n![Description image]({description_image})"
instance = hass.data.get(_KEY_INSTANCE)
+1 -1
View File
@@ -28,7 +28,7 @@ class DemoCamera(Camera):
self._images_index = (self._images_index + 1) % 4
image_path = os.path.join(
os.path.dirname(__file__), "demo_{}.jpg".format(self._images_index)
os.path.dirname(__file__), f"demo_{self._images_index}.jpg"
)
_LOGGER.debug("Loading camera_image: %s", image_path)
with open(image_path, "rb") as file:
@@ -417,7 +417,7 @@ class DemoTVShowPlayer(AbstractDemoPlayer):
@property
def media_title(self):
"""Return the title of current playing media."""
return "Chapter {}".format(self._cur_episode)
return f"Chapter {self._cur_episode}"
@property
def media_series_title(self):
+1 -1
View File
@@ -244,7 +244,7 @@ class DemoVacuum(VacuumDevice):
if self.supported_features & SUPPORT_SEND_COMMAND == 0:
return
self._status = "Executing {}({})".format(command, params)
self._status = f"Executing {command}({params})"
self._state = True
self.schedule_update_ha_state()
@@ -274,9 +274,7 @@ async def async_setup(hass, config):
("frontend_latest", True),
("frontend_es5", True),
):
hass.http.register_static_path(
"/{}".format(path), str(root_path / path), should_cache
)
hass.http.register_static_path(f"/{path}", str(root_path / path), should_cache)
hass.http.register_static_path(
"/auth/authorize", str(root_path / "authorize.html"), False
@@ -294,9 +292,7 @@ async def async_setup(hass, config):
# To smooth transition to new urls, add redirects to new urls of dev tools
# Added June 27, 2019. Can be removed in 2021.
for panel in ("event", "info", "service", "state", "template", "mqtt"):
hass.http.register_redirect(
"/dev-{}".format(panel), "/developer-tools/{}".format(panel)
)
hass.http.register_redirect(f"/dev-{panel}", f"/developer-tools/{panel}")
async_register_built_in_panel(
hass,
+1 -1
View File
@@ -271,7 +271,7 @@ async def async_setup(hass, config):
hass.components.persistent_notification.async_create(
"Config error. See dev-info panel for details.",
"Config validating",
"{0}.check_config".format(HASS_DOMAIN),
f"{HASS_DOMAIN}.check_config",
)
return
+3 -3
View File
@@ -80,7 +80,7 @@ class HassIO:
This method return a coroutine.
"""
return self.send_command("/addons/{}/info".format(addon), method="get")
return self.send_command(f"/addons/{addon}/info", method="get")
@_api_data
def get_ingress_panels(self):
@@ -120,7 +120,7 @@ class HassIO:
This method return a coroutine.
"""
return self.send_command("/discovery/{}".format(uuid), method="get")
return self.send_command(f"/discovery/{uuid}", method="get")
@_api_bool
async def update_hass_api(self, http_config, refresh_token):
@@ -156,7 +156,7 @@ class HassIO:
with async_timeout.timeout(timeout):
request = await self.websession.request(
method,
"http://{}{}".format(self._ip, command),
f"http://{self._ip}{command}",
json=payload,
headers={X_HASSIO: os.environ.get("HASSIO_TOKEN", "")},
)
+1 -1
View File
@@ -75,7 +75,7 @@ class HassIOView(HomeAssistantView):
method = getattr(self._websession, request.method.lower())
client = await method(
"http://{}/{}".format(self._host, path),
f"http://{self._host}/{path}",
data=data,
headers=headers,
timeout=read_timeout,
+5 -5
View File
@@ -42,7 +42,7 @@ class HassIOIngress(HomeAssistantView):
def _create_url(self, token: str, path: str) -> str:
"""Create URL to service."""
return "http://{}/ingress/{}/{}".format(self._host, token, path)
return f"http://{self._host}/ingress/{token}/{path}"
async def _handle(
self, request: web.Request, token: str, path: str
@@ -91,7 +91,7 @@ class HassIOIngress(HomeAssistantView):
# Support GET query
if request.query_string:
url = "{}?{}".format(url, request.query_string)
url = f"{url}?{request.query_string}"
# Start proxy
async with self._websession.ws_connect(
@@ -175,15 +175,15 @@ def _init_header(
headers[X_HASSIO] = os.environ.get("HASSIO_TOKEN", "")
# Ingress information
headers[X_INGRESS_PATH] = "/api/hassio_ingress/{}".format(token)
headers[X_INGRESS_PATH] = f"/api/hassio_ingress/{token}"
# Set X-Forwarded-For
forward_for = request.headers.get(hdrs.X_FORWARDED_FOR)
connected_ip = ip_address(request.transport.get_extra_info("peername")[0])
if forward_for:
forward_for = "{}, {!s}".format(forward_for, connected_ip)
forward_for = f"{forward_for}, {connected_ip!s}"
else:
forward_for = "{!s}".format(connected_ip)
forward_for = f"{connected_ip!s}"
headers[hdrs.X_FORWARDED_FOR] = forward_for
# Set X-Forwarded-Host
+5 -9
View File
@@ -133,12 +133,12 @@ class ApiConfig:
if host.startswith(("http://", "https://")):
self.base_url = host
elif use_ssl:
self.base_url = "https://{}".format(host)
self.base_url = f"https://{host}"
else:
self.base_url = "http://{}".format(host)
self.base_url = f"http://{host}"
if port is not None:
self.base_url += ":{}".format(port)
self.base_url += f":{port}"
async def async_setup(hass, config):
@@ -268,15 +268,11 @@ class HomeAssistantHTTP:
if not hasattr(view, "url"):
class_name = view.__class__.__name__
raise AttributeError(
'{0} missing required attribute "url"'.format(class_name)
)
raise AttributeError(f'{class_name} missing required attribute "url"')
if not hasattr(view, "name"):
class_name = view.__class__.__name__
raise AttributeError(
'{0} missing required attribute "name"'.format(class_name)
)
raise AttributeError(f'{class_name} missing required attribute "name"')
view.register(self.app, self.app.router)
+1 -1
View File
@@ -127,7 +127,7 @@ async def process_wrong_login(request):
_LOGGER.warning("Banned IP %s for too many login attempts", remote_addr)
hass.components.persistent_notification.async_create(
"Too many login attempts from {}".format(remote_addr),
f"Too many login attempts from {remote_addr}",
"Banning IP address",
NOTIFICATION_ID_BAN,
)
@@ -43,9 +43,7 @@ class RequestDataValidator:
kwargs["data"] = self._schema(data)
except vol.Invalid as err:
_LOGGER.error("Data does not match schema: %s", err)
return view.json_message(
"Message format incorrect: {}".format(err), 400
)
return view.json_message(f"Message format incorrect: {err}", 400)
result = await method(view, request, *args, **kwargs)
return result
+1 -1
View File
@@ -10,7 +10,7 @@ from aiohttp.web_urldispatcher import StaticResource
# mypy: allow-untyped-defs
CACHE_TIME = 31 * 86400 # = 1 month
CACHE_HEADERS = {hdrs.CACHE_CONTROL: "public, max-age={}".format(CACHE_TIME)}
CACHE_HEADERS = {hdrs.CACHE_CONTROL: f"public, max-age={CACHE_TIME}"}
# https://github.com/PyCQA/astroid/issues/633
@@ -49,13 +49,11 @@ def _cv_input_number(cfg):
maximum = cfg.get(CONF_MAX)
if minimum >= maximum:
raise vol.Invalid(
"Maximum ({}) is not greater than minimum ({})".format(minimum, maximum)
f"Maximum ({minimum}) is not greater than minimum ({maximum})"
)
state = cfg.get(CONF_INITIAL)
if state is not None and (state < minimum or state > maximum):
raise vol.Invalid(
"Initial value {} not in range {}-{}".format(state, minimum, maximum)
)
raise vol.Invalid(f"Initial value {state} not in range {minimum}-{maximum}")
return cfg
@@ -45,12 +45,12 @@ def _cv_input_text(cfg):
maximum = cfg.get(CONF_MAX)
if minimum > maximum:
raise vol.Invalid(
"Max len ({}) is not greater than min len ({})".format(minimum, maximum)
f"Max len ({minimum}) is not greater than min len ({maximum})"
)
state = cfg.get(CONF_INITIAL)
if state is not None and (len(state) < minimum or len(state) > maximum):
raise vol.Invalid(
"Initial value {} length not in range {}-{}".format(state, minimum, maximum)
f"Initial value {state} length not in range {minimum}-{maximum}"
)
return cfg
@@ -94,7 +94,7 @@ class IntegrationSensor(RestoreEntity):
self._state = 0
self._method = integration_method
self._name = name if name is not None else "{} integral".format(source_entity)
self._name = name if name is not None else f"{source_entity} integral"
if unit_of_measurement is None:
self._unit_template = "{}{}{}".format(
@@ -55,7 +55,7 @@ async def async_setup(hass, config):
for intent_type, conf in intents.items():
if CONF_ACTION in conf:
conf[CONF_ACTION] = script.Script(
hass, conf[CONF_ACTION], "Intent Script {}".format(intent_type)
hass, conf[CONF_ACTION], f"Intent Script {intent_type}"
)
intent.async_register(hass, ScriptIntentHandler(intent_type, conf))
@@ -113,7 +113,7 @@ def discover_scripts(hass):
@bind_hass
def execute_script(hass, name, data=None):
"""Execute a script."""
filename = "{}.py".format(name)
filename = f"{name}.py"
with open(hass.config.path(FOLDER, sanitize_filename(filename))) as fil:
source = fil.read()
execute(hass, filename, source, data)
@@ -166,9 +166,7 @@ def execute(hass, filename, source, data=None):
or isinstance(obj, TimeWrapper)
and name not in ALLOWED_TIME
):
raise ScriptError(
"Not allowed to access {}.{}".format(obj.__class__.__name__, name)
)
raise ScriptError(f"Not allowed to access {obj.__class__.__name__}.{name}")
return getattr(obj, name, default)
@@ -188,7 +186,7 @@ def execute(hass, filename, source, data=None):
"_iter_unpack_sequence_": guarded_iter_unpack_sequence,
"_unpack_sequence_": guarded_unpack_sequence,
}
logger = logging.getLogger("{}.{}".format(__name__, filename))
logger = logging.getLogger(f"{__name__}.{filename}")
local = {"hass": hass, "data": data or {}, "logger": logger}
try:
@@ -107,7 +107,7 @@ def _drop_index(engine, table_name, index_name):
# Engines like DB2/Oracle
try:
engine.execute(text("DROP INDEX {index}".format(index=index_name)))
engine.execute(text(f"DROP INDEX {index_name}"))
except SQLAlchemyError:
pass
else:
@@ -170,7 +170,7 @@ def _add_columns(engine, table_name, columns_def):
table_name,
)
columns_def = ["ADD {}".format(col_def) for col_def in columns_def]
columns_def = [f"ADD {col_def}" for col_def in columns_def]
try:
engine.execute(
@@ -265,9 +265,7 @@ def _apply_update(engine, new_version, old_version):
# 'context_parent_id CHARACTER(36)',
# ])
else:
raise ValueError(
"No schema migration defined for version {}".format(new_version)
)
raise ValueError(f"No schema migration defined for version {new_version}")
def _inspect_schema_version(engine, session):
+1 -1
View File
@@ -209,7 +209,7 @@ class ScriptEntity(ToggleEntity):
await self.script.async_run(kwargs.get(ATTR_VARIABLES), context)
except Exception as err: # pylint: disable=broad-except
self.script.async_log_exception(
_LOGGER, "Error executing script {}".format(self.entity_id), err
_LOGGER, f"Error executing script {self.entity_id}", err
)
raise err
@@ -198,7 +198,7 @@ async def async_setup(hass, config):
return
if service.service == "write":
logger = logging.getLogger(
service.data.get(CONF_LOGGER, "{}.external".format(__name__))
service.data.get(CONF_LOGGER, f"{__name__}.external")
)
level = service.data[CONF_LEVEL]
getattr(logger, level)(service.data[CONF_MESSAGE])
+11 -15
View File
@@ -165,9 +165,7 @@ async def async_setup(hass, config):
DOMAIN_MP, SERVICE_PLAY_MEDIA, data, blocking=True
)
service_name = p_config.get(
CONF_SERVICE_NAME, "{}_{}".format(p_type, SERVICE_SAY)
)
service_name = p_config.get(CONF_SERVICE_NAME, f"{p_type}_{SERVICE_SAY}")
hass.services.async_register(
DOMAIN, service_name, async_say_handle, schema=SCHEMA_SERVICE_SAY
)
@@ -229,7 +227,7 @@ class SpeechManager:
init_tts_cache_dir, cache_dir
)
except OSError as err:
raise HomeAssistantError("Can't init cache dir {}".format(err))
raise HomeAssistantError(f"Can't init cache dir {err}")
def get_cache_files():
"""Return a dict of given engine files."""
@@ -251,7 +249,7 @@ class SpeechManager:
try:
cache_files = await self.hass.async_add_job(get_cache_files)
except OSError as err:
raise HomeAssistantError("Can't read cache dir {}".format(err))
raise HomeAssistantError(f"Can't read cache dir {err}")
if cache_files:
self.file_cache.update(cache_files)
@@ -293,7 +291,7 @@ class SpeechManager:
# Languages
language = language or provider.default_language
if language is None or language not in provider.supported_languages:
raise HomeAssistantError("Not supported language {0}".format(language))
raise HomeAssistantError(f"Not supported language {language}")
# Options
if provider.default_options and options:
@@ -308,9 +306,7 @@ class SpeechManager:
if opt_name not in (provider.supported_options or [])
]
if invalid_opts:
raise HomeAssistantError(
"Invalid options found: {}".format(invalid_opts)
)
raise HomeAssistantError(f"Invalid options found: {invalid_opts}")
options_key = ctypes.c_size_t(hash(frozenset(options))).value
else:
options_key = "-"
@@ -330,7 +326,7 @@ class SpeechManager:
engine, key, message, use_cache, language, options
)
return "{}/api/tts_proxy/{}".format(self.base_url, filename)
return f"{self.base_url}/api/tts_proxy/{filename}"
async def async_get_tts_audio(self, engine, key, message, cache, language, options):
"""Receive TTS and store for view in cache.
@@ -341,10 +337,10 @@ class SpeechManager:
extension, data = await provider.async_get_tts_audio(message, language, options)
if data is None or extension is None:
raise HomeAssistantError("No TTS from {} for '{}'".format(engine, message))
raise HomeAssistantError(f"No TTS from {engine} for '{message}'")
# Create file infos
filename = ("{}.{}".format(key, extension)).lower()
filename = (f"{key}.{extension}").lower()
data = self.write_tags(filename, data, provider, message, language, options)
@@ -381,7 +377,7 @@ class SpeechManager:
"""
filename = self.file_cache.get(key)
if not filename:
raise HomeAssistantError("Key {} not in file cache!".format(key))
raise HomeAssistantError(f"Key {key} not in file cache!")
voice_file = os.path.join(self.cache_dir, filename)
@@ -394,7 +390,7 @@ class SpeechManager:
data = await self.hass.async_add_job(load_speech)
except OSError:
del self.file_cache[key]
raise HomeAssistantError("Can't read {}".format(voice_file))
raise HomeAssistantError(f"Can't read {voice_file}")
self._async_store_to_memcache(key, filename, data)
@@ -425,7 +421,7 @@ class SpeechManager:
if key not in self.mem_cache:
if key not in self.file_cache:
raise HomeAssistantError("{} not in cache!".format(key))
raise HomeAssistantError(f"{key} not in cache!")
await self.async_file_to_mem(key)
content, _ = mimetypes.guess_type(filename)
@@ -98,7 +98,7 @@ async def async_setup(hass, config):
tariff_confs.append(
{
CONF_METER: meter,
CONF_NAME: "{} {}".format(meter, tariff),
CONF_NAME: f"{meter} {tariff}",
CONF_TARIFF: tariff,
}
)
@@ -107,7 +107,7 @@ class UtilityMeterSensor(RestoreEntity):
if name:
self._name = name
else:
self._name = "{} meter".format(source_entity)
self._name = f"{source_entity} meter"
self._unit_of_measurement = None
self._period = meter_type
self._period_offset = meter_offset
@@ -33,7 +33,7 @@ CONFIG_SCHEMA = vol.Schema({DOMAIN: vol.Schema({})}, extra=vol.ALLOW_EXTRA)
def setup(hass, config):
"""Set up Zeroconf and make Home Assistant discoverable."""
zeroconf_name = "{}.{}".format(hass.config.location_name, ZEROCONF_TYPE)
zeroconf_name = f"{hass.config.location_name}.{ZEROCONF_TYPE}"
params = {
"version": __version__,