Skip to content
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

Use f-strings in integrations starting with "H" - "L" #32265

Merged
merged 15 commits into from Feb 28, 2020
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion homeassistant/components/habitica/__init__.py
Expand Up @@ -80,7 +80,7 @@ def has_all_unique_users_names(value):
ATTR_NAME = CONF_NAME
ATTR_PATH = CONF_PATH
ATTR_ARGS = "args"
EVENT_API_CALL_SUCCESS = "{0}_{1}_{2}".format(DOMAIN, SERVICE_API_CALL, "success")
EVENT_API_CALL_SUCCESS = f"{DOMAIN}_{SERVICE_API_CALL}_success"

SERVICE_API_CALL_SCHEMA = vol.Schema(
{
Expand Down
4 changes: 1 addition & 3 deletions homeassistant/components/harmony/remote.py
Expand Up @@ -111,9 +111,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
activity,
)

harmony_conf_file = hass.config.path(
"{}{}{}".format("harmony_", slugify(name), ".conf")
)
harmony_conf_file = hass.config.path(f"harmony_{slugify(name)}.conf")
try:
device = HarmonyRemote(
name, address, port, activity, harmony_conf_file, delay_secs
Expand Down
10 changes: 4 additions & 6 deletions homeassistant/components/haveibeenpwned/sensor.py
Expand Up @@ -81,12 +81,10 @@ def device_state_attributes(self):
return val

for idx, value in enumerate(self._data.data[self._email]):
tmpname = "breach {}".format(idx + 1)
tmpvalue = "{} {}".format(
value["Title"],
dt_util.as_local(dt_util.parse_datetime(value["AddedDate"])).strftime(
DATE_STR_FORMAT
),
tmpname = f"breach {idx + 1}"
tmpvalue = (
f"{value['Title']} "
f"{dt_util.as_local(dt_util.parse_datetime(value['AddedDate'])).strftime(DATE_STR_FORMAT)}"
springstan marked this conversation as resolved.
Show resolved Hide resolved
)
val[tmpname] = tmpvalue

Expand Down
4 changes: 1 addition & 3 deletions homeassistant/components/heos/config_flow.py
Expand Up @@ -27,9 +27,7 @@ async def async_step_ssdp(self, discovery_info):
"""Handle a discovered Heos device."""
# Store discovered host
hostname = urlparse(discovery_info[ssdp.ATTR_SSDP_LOCATION]).hostname
friendly_name = "{} ({})".format(
discovery_info[ssdp.ATTR_UPNP_FRIENDLY_NAME], hostname
)
friendly_name = f"{discovery_info[ssdp.ATTR_UPNP_FRIENDLY_NAME]} ({hostname})"
self.hass.data.setdefault(DATA_DISCOVERED_HOSTS, {})
self.hass.data[DATA_DISCOVERED_HOSTS][friendly_name] = hostname
# Abort if other flows in progress or an entry already exists
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/here_travel_time/sensor.py
Expand Up @@ -315,7 +315,7 @@ async def _get_location_from_entity(self, entity_id: str) -> Optional[str]:
return self._get_location_from_attributes(entity)

# Check if device is in a zone
zone_entity = self.hass.states.get("zone.{}".format(entity.state))
zone_entity = self.hass.states.get(f"zone.{entity.state}")
if location.has_location(zone_entity):
_LOGGER.debug(
"%s is in %s, getting zone location", entity_id, zone_entity.entity_id
Expand Down Expand Up @@ -348,7 +348,7 @@ def _entity_state_is_valid_coordinate_set(state: str) -> bool:
def _get_location_from_attributes(entity: State) -> str:
"""Get the lat/long string from an entities attributes."""
attr = entity.attributes
return "{},{}".format(attr.get(ATTR_LATITUDE), attr.get(ATTR_LONGITUDE))
return f"{attr.get(ATTR_LATITUDE)},{attr.get(ATTR_LONGITUDE)}"


class HERETravelTimeData:
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/hikvision/binary_sensor.py
Expand Up @@ -109,7 +109,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
for channel in channel_list:
# Build sensor name, then parse customize config.
if data.type == "NVR":
sensor_name = "{}_{}".format(sensor.replace(" ", "_"), channel[1])
sensor_name = f"{sensor.replace(' ', '_')}_{channel[1]}"
else:
sensor_name = sensor.replace(" ", "_")

Expand Down
8 changes: 3 additions & 5 deletions homeassistant/components/hlk_sw16/__init__.py
Expand Up @@ -30,8 +30,6 @@

DOMAIN = "hlk_sw16"

SIGNAL_AVAILABILITY = "hlk_sw16_device_available_{}"

SWITCH_SCHEMA = vol.Schema({vol.Optional(CONF_NAME): cv.string})

RELAY_ID = vol.All(
Expand Down Expand Up @@ -74,13 +72,13 @@ def add_device(device):
def disconnected():
"""Schedule reconnect after connection has been lost."""
_LOGGER.warning("HLK-SW16 %s disconnected", device)
async_dispatcher_send(hass, SIGNAL_AVAILABILITY.format(device), False)
async_dispatcher_send(hass, f"hlk_sw16_device_available_{device}", False)

@callback
def reconnected():
"""Schedule reconnect after connection has been lost."""
_LOGGER.warning("HLK-SW16 %s connected", device)
async_dispatcher_send(hass, SIGNAL_AVAILABILITY.format(device), True)
async_dispatcher_send(hass, f"hlk_sw16_device_available_{device}", True)

async def connect():
"""Set up connection and hook it into HA for reconnect/shutdown."""
Expand Down Expand Up @@ -168,6 +166,6 @@ async def async_added_to_hass(self):
self._is_on = await self._client.status(self._device_port)
async_dispatcher_connect(
self.hass,
SIGNAL_AVAILABILITY.format(self._device_id),
f"hlk_sw16_device_available_{self._device_id}",
self._availability_callback,
)
4 changes: 2 additions & 2 deletions homeassistant/components/homekit/type_media_players.py
Expand Up @@ -146,7 +146,7 @@ def __init__(self, *args):

def generate_service_name(self, mode):
"""Generate name for individual service."""
return "{} {}".format(self.display_name, MODE_FRIENDLY_NAME[mode])
return f"{self.display_name} {MODE_FRIENDLY_NAME[mode]}"

def set_on_off(self, value):
"""Move switch state to value if call came from HomeKit."""
Expand Down Expand Up @@ -287,7 +287,7 @@ def __init__(self, *args):
)
serv_tv.add_linked_service(serv_speaker)

name = "{} {}".format(self.display_name, "Volume")
name = f"{self.display_name} Volume"
serv_speaker.configure_char(CHAR_NAME, value=name)
serv_speaker.configure_char(CHAR_ACTIVE, value=1)

Expand Down
8 changes: 3 additions & 5 deletions homeassistant/components/homekit/util.py
Expand Up @@ -102,9 +102,7 @@ def validate_entity_config(values):
domain, _ = split_entity_id(entity)

if not isinstance(config, dict):
raise vol.Invalid(
"The configuration for {} must be a dictionary.".format(entity)
)
raise vol.Invalid(f"The configuration for {entity} must be a dictionary.")

if domain in ("alarm_control_panel", "lock"):
config = CODE_SCHEMA(config)
Expand Down Expand Up @@ -212,8 +210,8 @@ def show_setup_message(hass, pincode):
pin = pincode.decode()
_LOGGER.info("Pincode: %s", pin)
message = (
"To set up Home Assistant in the Home App, enter the "
"following code:\n### {}".format(pin)
f"To set up Home Assistant in the Home App, enter the "
f"following code:\n### {pin}"
)
hass.components.persistent_notification.create(
message, "HomeKit Setup", HOMEKIT_NOTIFY_ID
Expand Down
Expand Up @@ -73,7 +73,7 @@ def ensure_pin_format(pin):
match = PIN_FORMAT.search(pin)
if not match:
raise aiohomekit.exceptions.MalformedPinError(f"Invalid PIN code f{pin}")
return "{}-{}-{}".format(*match.groups())
return f"{match.groups()[0]}-{match.groups()[1]}-{match.groups()[2]}"
springstan marked this conversation as resolved.
Show resolved Hide resolved


@config_entries.HANDLERS.register(DOMAIN)
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/homematic/entity.py
Expand Up @@ -200,7 +200,7 @@ class HMHub(Entity):
def __init__(self, hass, homematic, name):
"""Initialize HomeMatic hub."""
self.hass = hass
self.entity_id = "{}.{}".format(DOMAIN, name.lower())
self.entity_id = f"{DOMAIN}.{name.lower()}"
self._homematic = homematic
self._variables = {}
self._name = name
Expand Down
5 changes: 2 additions & 3 deletions homeassistant/components/homeworks/__init__.py
Expand Up @@ -22,7 +22,6 @@
DOMAIN = "homeworks"

HOMEWORKS_CONTROLLER = "homeworks"
ENTITY_SIGNAL = "homeworks_entity_{}"
EVENT_BUTTON_PRESS = "homeworks_button_press"
EVENT_BUTTON_RELEASE = "homeworks_button_release"

Expand Down Expand Up @@ -71,7 +70,7 @@ def hw_callback(msg_type, values):
"""Dispatch state changes."""
_LOGGER.debug("callback: %s, %s", msg_type, values)
addr = values[0]
signal = ENTITY_SIGNAL.format(addr)
signal = f"homeworks_entity_{addr}"
dispatcher_send(hass, signal, msg_type, values)

config = base_config.get(DOMAIN)
Expand Down Expand Up @@ -132,7 +131,7 @@ def __init__(self, hass, addr, name):
self._addr = addr
self._name = name
self._id = slugify(self._name)
signal = ENTITY_SIGNAL.format(self._addr)
signal = f"homeworks_entity_{self._addr}"
async_dispatcher_connect(self._hass, signal, self._update_callback)

@callback
Expand Down
3 changes: 1 addition & 2 deletions homeassistant/components/homeworks/light.py
Expand Up @@ -12,7 +12,6 @@
CONF_ADDR,
CONF_DIMMERS,
CONF_RATE,
ENTITY_SIGNAL,
HOMEWORKS_CONTROLLER,
HomeworksDevice,
)
Expand Down Expand Up @@ -47,7 +46,7 @@ def __init__(self, controller, addr, name, rate):

async def async_added_to_hass(self):
"""Call when entity is added to hass."""
signal = ENTITY_SIGNAL.format(self._addr)
signal = f"homeworks_entity_{self._addr}"
_LOGGER.debug("connecting %s", signal)
async_dispatcher_connect(self.hass, signal, self._update_callback)
self._controller.request_dimmer_level(self._addr)
Expand Down
4 changes: 1 addition & 3 deletions homeassistant/components/hp_ilo/sensor.py
Expand Up @@ -90,9 +90,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
new_device = HpIloSensor(
hass=hass,
hp_ilo_data=hp_ilo_data,
sensor_name="{} {}".format(
config.get(CONF_NAME), monitored_variable[CONF_NAME]
),
sensor_name=f"{config.get(CONF_NAME)} {monitored_variable[CONF_NAME]}",
sensor_type=monitored_variable[CONF_SENSOR_TYPE],
sensor_value_template=monitored_variable.get(CONF_VALUE_TEMPLATE),
unit_of_measurement=monitored_variable.get(CONF_UNIT_OF_MEASUREMENT),
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/html5/notify.py
Expand Up @@ -392,7 +392,7 @@ async def post(self, request):
humanize_error(event_payload, ex),
)

event_name = "{}.{}".format(NOTIFY_CALLBACK_EVENT, event_payload[ATTR_TYPE])
event_name = f"{NOTIFY_CALLBACK_EVENT}.{event_payload[ATTR_TYPE]}"
request.app["hass"].bus.fire(event_name, event_payload)
return self.json({"status": "ok", "event": event_payload[ATTR_TYPE]})

Expand Down
16 changes: 3 additions & 13 deletions homeassistant/components/http/auth.py
Expand Up @@ -29,19 +29,9 @@ def async_sign_path(hass, refresh_token_id, path, expiration):
secret = hass.data[DATA_SIGN_SECRET] = secrets.token_hex()

now = dt_util.utcnow()
return "{}?{}={}".format(
path,
SIGN_QUERY_PARAM,
jwt.encode(
{
"iss": refresh_token_id,
"path": path,
"iat": now,
"exp": now + expiration,
},
secret,
algorithm="HS256",
).decode(),
return (
f"{path}?{SIGN_QUERY_PARAM}="
f"{jwt.encode({'iss': refresh_token_id,'path': path,'iat': now,'exp': now + expiration,},secret,algorithm='HS256',).decode()}"
springstan marked this conversation as resolved.
Show resolved Hide resolved
)


Expand Down
4 changes: 1 addition & 3 deletions homeassistant/components/http/ban.py
Expand Up @@ -96,9 +96,7 @@ async def process_wrong_login(request):
"""
remote_addr = request[KEY_REAL_IP]

msg = "Login attempt or request with invalid authentication from {}".format(
remote_addr
)
msg = f"Login attempt or request with invalid authentication from {remote_addr}"
_LOGGER.warning(msg)

hass = request.app["hass"]
Expand Down
4 changes: 1 addition & 3 deletions homeassistant/components/http/view.py
Expand Up @@ -144,9 +144,7 @@ async def handle(request):
elif not isinstance(result, bytes):
assert (
False
), "Result should be None, string, bytes or Response. Got: {}".format(
result
)
), f"Result should be None, string, bytes or Response. Got: {result}"

return web.Response(body=result, status=status_code)

Expand Down
4 changes: 1 addition & 3 deletions homeassistant/components/huawei_lte/__init__.py
Expand Up @@ -81,8 +81,6 @@
# https://github.com/quandyfactory/dicttoxml/issues/60
logging.getLogger("dicttoxml").setLevel(logging.WARNING)

DEFAULT_NAME_TEMPLATE = "Huawei {} {}"

SCAN_INTERVAL = timedelta(seconds=10)

NOTIFY_SCHEMA = vol.Any(
Expand Down Expand Up @@ -567,7 +565,7 @@ def unique_id(self) -> str:
@property
def name(self) -> str:
"""Return entity name."""
return DEFAULT_NAME_TEMPLATE.format(self.router.device_name, self._entity_name)
return f"Huawei {self.router.device_name} {self._entity_name}"

@property
def available(self) -> bool:
Expand Down
9 changes: 2 additions & 7 deletions homeassistant/components/hydrawise/__init__.py
Expand Up @@ -84,9 +84,7 @@ def setup(hass, config):
except (ConnectTimeout, HTTPError) as ex:
_LOGGER.error("Unable to connect to Hydrawise 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,
)
Expand Down Expand Up @@ -119,10 +117,7 @@ def __init__(self, data, sensor_type):
"""Initialize the Hydrawise entity."""
self.data = data
self._sensor_type = sensor_type
self._name = "{0} {1}".format(
self.data["name"],
DEVICE_MAP[self._sensor_type][DEVICE_MAP_INDEX.index("KEY_INDEX")],
)
self._name = f"{self.data['name']} {DEVICE_MAP[self._sensor_type][DEVICE_MAP_INDEX.index('KEY_INDEX')]}"
self._state = None

@property
Expand Down
11 changes: 4 additions & 7 deletions homeassistant/components/ign_sismologia/geo_location.py
Expand Up @@ -37,9 +37,6 @@

SCAN_INTERVAL = timedelta(minutes=5)

SIGNAL_DELETE_ENTITY = "ign_sismologia_delete_{}"
SIGNAL_UPDATE_ENTITY = "ign_sismologia_update_{}"

SOURCE = "ign_sismologia"

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
Expand Down Expand Up @@ -124,11 +121,11 @@ def _generate_entity(self, external_id):

def _update_entity(self, external_id):
"""Update entity."""
dispatcher_send(self._hass, SIGNAL_UPDATE_ENTITY.format(external_id))
dispatcher_send(self._hass, f"ign_sismologia_update_{external_id}")

def _remove_entity(self, external_id):
"""Remove entity."""
dispatcher_send(self._hass, SIGNAL_DELETE_ENTITY.format(external_id))
dispatcher_send(self._hass, f"ign_sismologia_delete_{external_id}")


class IgnSismologiaLocationEvent(GeolocationEvent):
Expand All @@ -154,12 +151,12 @@ async def async_added_to_hass(self):
"""Call when entity is added to hass."""
self._remove_signal_delete = async_dispatcher_connect(
self.hass,
SIGNAL_DELETE_ENTITY.format(self._external_id),
f"ign_sismologia_delete_{self._external_id}",
self._delete_callback,
)
self._remove_signal_update = async_dispatcher_connect(
self.hass,
SIGNAL_UPDATE_ENTITY.format(self._external_id),
f"ign_sismologia_update_{self._external_id}",
self._update_callback,
)

Expand Down
3 changes: 1 addition & 2 deletions homeassistant/components/ihc/__init__.py
Expand Up @@ -53,7 +53,6 @@
DOMAIN = "ihc"

IHC_CONTROLLER = "controller"
IHC_DATA = "ihc{}"
IHC_INFO = "info"
IHC_PLATFORMS = ("binary_sensor", "light", "sensor", "switch")

Expand Down Expand Up @@ -236,7 +235,7 @@ def ihc_setup(hass, config, conf, controller_id):
# Manual configuration
get_manual_configuration(hass, config, conf, ihc_controller, controller_id)
# Store controller configuration
ihc_key = IHC_DATA.format(controller_id)
ihc_key = f"ihc{controller_id}"
hass.data[ihc_key] = {IHC_CONTROLLER: ihc_controller, IHC_INFO: conf[CONF_INFO]}
setup_service_functions(hass, ihc_controller)
return True
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/ihc/binary_sensor.py
Expand Up @@ -2,7 +2,7 @@
from homeassistant.components.binary_sensor import BinarySensorDevice
from homeassistant.const import CONF_TYPE

from . import IHC_CONTROLLER, IHC_DATA, IHC_INFO
from . import IHC_CONTROLLER, IHC_INFO
from .const import CONF_INVERTING
from .ihcdevice import IHCDevice

Expand All @@ -18,7 +18,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
product = device["product"]
# Find controller that corresponds with device id
ctrl_id = device["ctrl_id"]
ihc_key = IHC_DATA.format(ctrl_id)
ihc_key = f"ihc{ctrl_id}"
info = hass.data[ihc_key][IHC_INFO]
ihc_controller = hass.data[ihc_key][IHC_CONTROLLER]

Expand Down