8000 Use literal string interpolation in core (f-strings) by frenck · Pull Request #26166 · home-assistant/core · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 23, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions homeassistant/__main__.py
F438
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ def get_arguments() -> argparse.Namespace:
parser.add_argument(
"--runner",
action="store_true",
help="On restart exit with code {}".format(RESTART_EXIT_CODE),
help=f"On restart exit with code {RESTART_EXIT_CODE}",
)
parser.add_argument(
"--script", nargs=argparse.REMAINDER, help="Run one of the embedded scripts"
Expand Down Expand Up @@ -240,7 +240,7 @@ def write_pid(pid_file: str) -> None:
with open(pid_file, "w") as file:
file.write(str(pid))
except IOError:
print("Fatal Error: Unable to write pid file {}".format(pid_file))
print(f"Fatal Error: Unable to write pid file {pid_file}")
sys.exit(1)


Expand Down Expand Up @@ -326,7 +326,7 @@ def try_to_restart() -> None:
thread.is_alive() and not thread.daemon for thread in threading.enumerate()
)
if nthreads > 1:
sys.stderr.write("Found {} non-daemonic threads.\n".format(nthreads))
sys.stderr.write(f"Found {nthreads} non-daemonic threads.\n")

# Somehow we sometimes seem to trigger an assertion in the python threading
# module. It seems we find threads that have no associated OS level thread
Expand Down
10 changes: 3 additions & 7 deletions homeassistant/auth/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,9 +278,7 @@ async def async_enable_user_mfa(

module = self.get_auth_mfa_module(mfa_module_id)
if module is None:
raise ValueError(
"Unable find multi-factor auth module: {}".format(mfa_module_id)
)
raise ValueError(f"Unable find multi-factor auth module: {mfa_module_id}")

await module.async_setup_user(user.id, data)

Expand All @@ -295,9 +293,7 @@ async def async_disable_user_mfa(

module = self.get_auth_mfa_module(mfa_module_id)
if module is None:
raise ValueError(
"Unable find multi-factor auth module: {}".format(mfa_module_id)
)
raise ValueError(f"Unable find multi-factor auth module: {mfa_module_id}")

await module.async_depose_user(user.id)

Expand Down Expand Up @@ -356,7 +352,7 @@ async def async_create_refresh_token(
):
# Each client_name can only have one
# long_lived_access_token type of refresh token
raise ValueError("{} already exists".format(client_name))
raise ValueError(f"{client_name} already exists")

return await self._store.async_create_refresh_token(
user,
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/auth/auth_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ async def async_create_user(
for group_id in group_ids or []:
group = self._groups.get(group_id)
if group is None:
raise ValueError("Invalid group specified {}".format(group_id))
raise ValueError(f"Invalid group specified {group_id}")
groups.append(group)

kwargs = {
Expand Down
6 changes: 2 additions & 4 deletions homeassistant/auth/mfa_modules/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,15 +144,13 @@ async def auth_mfa_module_from_config(

async def _load_mfa_module(hass: HomeAssistant, module_name: str) -> types.ModuleType:
"""Load an mfa auth module."""
module_path = "homeassistant.auth.mfa_modules.{}".format(module_name)
module_path = f"homeassistant.auth.mfa_modules.{module_name}"

try:
module = importlib.import_module(module_path)
except ImportError as err:
_LOGGER.error("Unable to load mfa module %s: %s", module_name, err)
raise HomeAssistantError(
"Unable to load mfa module {}: {}".format(module_name, err)
)
raise HomeAssistantError(f"Unable to load mfa module {module_name}: {err}")

if hass.config.skip_pip or not hasattr(module, "REQUIREMENTS"):
return module
Expand Down
10 changes: 3 additions & 7 deletions homeassistant/auth/providers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,14 +144,10 @@ async def load_auth_provider_module(
) -> types.ModuleType:
"""Load an auth provider."""
try:
module = importlib.import_module(
"homeassistant.auth.providers.{}".format(provider)
)
module = importlib.import_module(f"homeassistant.auth.providers.{provider}")
except ImportError as err:
_LOGGER.error("Unable to load auth provider %s: %s", provider, err)
raise HomeAssistantError(
"Unable to load auth provider {}: {}".format(provider, err)
)
raise HomeAssistantError(f"Unable to load auth provider {provider}: {err}")

if hass.config.skip_pip or not hasattr(module, "REQUIREMENTS"):
return module
Expand All @@ -166,7 +162,7 @@ async def load_auth_provider_module(
# https://github.com/python/mypy/issues/1424
reqs = module.REQUIREMENTS # type: ignore
await requirements.async_process_requirements(
hass, "auth provider {}".format(provider), reqs
hass, f"auth provider {provider}", reqs
)

processed.add(provider)
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ def async_enable_logging(
# ensure that the handlers it sets up wraps the correct streams.
logging.basicConfig(level=logging.INFO)

colorfmt = "%(log_color)s{}%(reset)s".format(fmt)
colorfmt = f"%(log_color)s{fmt}%(reset)s"
logging.getLogger().handlers[0].setFormatter(
ColoredFormatter(
colorfmt,
Expand Down
6 changes: 3 additions & 3 deletions homeassistant/components/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ async def forward_events(event):
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:
Expand Down Expand Up @@ -316,7 +316,7 @@ async def post(self, request, event_type):
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):
Expand Down Expand Up @@ -388,7 +388,7 @@ async def post(self, request):
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
)


Expand Down
6 changes: 3 additions & 3 deletions homeassistant/components/automation/__init__.py
Original file line number Diff line number Diff line change
B41A Expand Up @@ -143,7 +143,7 @@ async def trigger_service_handler(service_call):
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)())

Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -431,7 +431,7 @@ async def action(entity_id, variables, context):
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
Expand Down
12 changes: 6 additions & 6 deletions homeassistant/components/config/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,15 @@ 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

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
Expand Down Expand Up @@ -82,8 +82,8 @@ def __init__(
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
Expand Down Expand Up @@ -126,14 +126,14 @@ async def post(self, request, config_key):
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)
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/configurator/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/demo/camera.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def camera_image(self):
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:
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/demo/media_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -417,7 +417,7 @@ def media_image_url(self):
@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):
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/demo/vacuum.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ def send_command(self, command, params=None, **kwargs):
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()

Expand Down
8 changes: 2 additions & 6 deletions homeassistant/components/frontend/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/hassio/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ async def async_handle_core_service(call):
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

Expand Down
6 changes: 3 additions & 3 deletions homeassistant/components/hassio/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def get_addon_info(self, addon):

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):
Expand Down Expand Up @@ -120,7 +120,7 @@ def get_discovery_message(self, uuid):

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):
Expand Down Expand Up @@ -156,7 +156,7 @@ async def send_command(self, command, method="post", payload=None, timeout=10):
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", "")},
)
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/hassio/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ async def _command_proxy(

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,
Expand Down
10 changes: 5 additions & 5 deletions homeassistant/components/hassio/ingress.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def __init__(self, host: str, websession: aiohttp.ClientSession):

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
Expand Down Expand Up @@ -91,7 +91,7 @@ async def _handle_websocket(

# 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(
Expand Down Expand Up @@ -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
Expand Down
14 changes: 5 additions & 9 deletions homeassistant/components/http/__init__.py
< 85B3 td id="diff-e0b98f199488aabeef7a7e252c286220dd94eecaeef8e171c1aebd46b54343aaL144" data-line-number="144" class="blob-num blob-num-context js-linkable-line-number">
Original file line number Diff line number Diff line change
Expand Up @@ -133,12 +133,12 @@ def __init__(
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):
Expand Down Expand Up @@ -268,15 +268,11 @@ def register_view(self, view):

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)

Expand Down
Loading
0