Skip to content

Commit

Permalink
Various string cleanups (home-assistant#30435)
Browse files Browse the repository at this point in the history
* Remove some unnecessary string concatenations

* Replace some simple str.formats with f-strings

* Replace some string concatenations with f-strings
  • Loading branch information
scop authored and balloob committed Jan 3, 2020
1 parent 5ad209c commit fa4fa30
Show file tree
Hide file tree
Showing 105 changed files with 241 additions and 314 deletions.
14 changes: 5 additions & 9 deletions homeassistant/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,21 +55,17 @@ def ensure_config_path(config_dir: str) -> None:
if not os.path.isdir(config_dir):
if config_dir != config_util.get_default_config_dir():
print(
(
"Fatal Error: Specified configuration directory does "
"not exist {} "
).format(config_dir)
f"Fatal Error: Specified configuration directory {config_dir} "
"does not exist"
)
sys.exit(1)

try:
os.mkdir(config_dir)
except OSError:
print(
(
"Fatal Error: Unable to create default configuration "
"directory {} "
).format(config_dir)
"Fatal Error: Unable to create default configuration "
f"directory {config_dir}"
)
sys.exit(1)

Expand All @@ -78,7 +74,7 @@ def ensure_config_path(config_dir: str) -> None:
try:
os.mkdir(lib_dir)
except OSError:
print("Fatal Error: Unable to create library directory {}".format(lib_dir))
print(f"Fatal Error: Unable to create library directory {lib_dir}")
sys.exit(1)


Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/apns/notify.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ def __init__(self, hass, app_name, topic, sandbox, cert_file):
self.app_name = app_name
self.sandbox = sandbox
self.certificate = cert_file
self.yaml_path = hass.config.path(app_name + "_" + APNS_DEVICES)
self.yaml_path = hass.config.path(f"{app_name}_{APNS_DEVICES}")
self.devices = {}
self.device_states = {}
self.topic = topic
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/braviatv/media_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ def media_title(self):
if self._channel_name is not None:
return_value = self._channel_name
if self._program_name is not None:
return_value = return_value + ": " + self._program_name
return_value = f"{return_value}: {self._program_name}"
return return_value

@property
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/cloud/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ def async_remote_ui_url(hass) -> str:
if not hass.data[DOMAIN].remote.instance_domain:
raise CloudNotAvailable

return "https://" + hass.data[DOMAIN].remote.instance_domain
return f"https://{hass.data[DOMAIN].remote.instance_domain}"


def is_cloudhook_request(request):
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/darksky/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -750,7 +750,7 @@ def get_state(self, data):
for i, alert in enumerate(data):
for attr in ALERTS_ATTRS:
if multiple_alerts:
dkey = attr + "_" + str(i)
dkey = f"{attr}_{i!s}"
else:
dkey = attr
alerts[dkey] = getattr(alert, attr)
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/ebusd/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def verify_ebusd_config(config):
circuit = config[CONF_CIRCUIT]
for condition in config[CONF_MONITORED_CONDITIONS]:
if condition not in SENSOR_TYPES[circuit]:
raise vol.Invalid("Condition '" + condition + "' not in '" + circuit + "'.")
raise vol.Invalid(f"Condition '{condition}' not in '{circuit}'.")
return config


Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/ecoal_boiler/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
_LOGGER = logging.getLogger(__name__)

DOMAIN = "ecoal_boiler"
DATA_ECOAL_BOILER = "data_" + DOMAIN
DATA_ECOAL_BOILER = f"data_{DOMAIN}"

DEFAULT_USERNAME = "admin"
DEFAULT_PASSWORD = "admin"
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/ecoal_boiler/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def __init__(self, ecoal_contr, name, state_attr):
# set_<attr>()
# as attribute name in status instance:
# status.<attr>
self._contr_set_fun = getattr(self._ecoal_contr, "set_" + state_attr)
self._contr_set_fun = getattr(self._ecoal_contr, f"set_{state_attr}")
# No value set, will be read from controller instead
self._state = None

Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/egardia/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ def setup(hass, config):
bound = server.bind()
if not bound:
raise OSError(
"Binding error occurred while " + "starting EgardiaServer."
"Binding error occurred while starting EgardiaServer."
)
hass.data[EGARDIA_SERVER] = server
server.start()
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/fibaro/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ def _read_devices(self):
else:
room_name = self._room_map[device.roomID].name
device.room_name = room_name
device.friendly_name = room_name + " " + device.name
device.friendly_name = f"{room_name} {device.name}"
device.ha_id = "{}_{}_{}".format(
slugify(room_name), slugify(device.name), device.id
)
Expand Down
8 changes: 4 additions & 4 deletions homeassistant/components/hangouts/hangouts_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,15 +86,15 @@ def async_update_conversation_commands(self):
conv_id = self._resolve_conversation_id(conversation)
if conv_id is not None:
conversations.append(conv_id)
data["_" + CONF_CONVERSATIONS] = conversations
data[f"_{CONF_CONVERSATIONS}"] = conversations
elif self._default_conv_ids:
data["_" + CONF_CONVERSATIONS] = self._default_conv_ids
data[f"_{CONF_CONVERSATIONS}"] = self._default_conv_ids
else:
data["_" + CONF_CONVERSATIONS] = [
data[f"_{CONF_CONVERSATIONS}"] = [
conv.id_ for conv in self._conversation_list.get_all()
]

for conv_id in data["_" + CONF_CONVERSATIONS]:
for conv_id in data[f"_{CONF_CONVERSATIONS}"]:
if conv_id not in self._conversation_intents:
self._conversation_intents[conv_id] = {}

Expand Down
6 changes: 2 additions & 4 deletions homeassistant/components/hook/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,10 @@
vol.Exclusive(
CONF_PASSWORD,
"hook_secret",
msg="hook: provide " + "username/password OR token",
msg="hook: provide username/password OR token",
): cv.string,
vol.Exclusive(
CONF_TOKEN,
"hook_secret",
msg="hook: provide " + "username/password OR token",
CONF_TOKEN, "hook_secret", msg="hook: provide username/password OR token",
): cv.string,
vol.Inclusive(CONF_USERNAME, "hook_auth"): cv.string,
vol.Inclusive(CONF_PASSWORD, "hook_auth"): cv.string,
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/huawei_router/device_tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ def _update_info(self):

_LOGGER.debug(
"Active clients: %s",
"\n".join((client.mac + " " + client.name) for client in active_clients),
"\n".join(f"{client.mac} {client.name}" for client in active_clients),
)
return True

Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/icloud/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ def _get_account(account_identifier: str) -> any:

if icloud_account is None:
raise Exception(
"No iCloud account with username or name " + account_identifier
f"No iCloud account with username or name {account_identifier}"
)
return icloud_account

Expand Down Expand Up @@ -430,7 +430,7 @@ def get_devices_with_name(self, name: str) -> [any]:
if slugify(device.name.replace(" ", "", 99)) == name_slug:
result.append(device)
if not result:
raise Exception("No device with name " + name)
raise Exception(f"No device with name {name}")
return result

@property
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/insteon/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -614,7 +614,7 @@ def name(self):
# Get an extension label if there is one
extension = self._get_label()
if extension:
extension = " " + extension
extension = f" {extension}"
name = "{:s} {:s}{:s}".format(
description, self._insteon_device.address.human, extension
)
Expand Down
12 changes: 6 additions & 6 deletions homeassistant/components/itunes/media_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ def _request(self, method, path, params=None):

def _command(self, named_command):
"""Make a request for a controlling command."""
return self._request("PUT", "/" + named_command)
return self._request("PUT", f"/{named_command}")

def now_playing(self):
"""Return the current state."""
Expand Down Expand Up @@ -168,25 +168,25 @@ def play_playlist(self, playlist_id_or_name):

def artwork_url(self):
"""Return a URL of the current track's album art."""
return self._base_url + "/artwork"
return f"{self._base_url}/artwork"

def airplay_devices(self):
"""Return a list of AirPlay devices."""
return self._request("GET", "/airplay_devices")

def airplay_device(self, device_id):
"""Return an AirPlay device."""
return self._request("GET", "/airplay_devices/" + device_id)
return self._request("GET", f"/airplay_devices/{device_id}")

def toggle_airplay_device(self, device_id, toggle):
"""Toggle airplay device on or off, id, toggle True or False."""
command = "on" if toggle else "off"
path = "/airplay_devices/" + device_id + "/" + command
path = f"/airplay_devices/{device_id}/{command}"
return self._request("PUT", path)

def set_volume_airplay_device(self, device_id, level):
"""Set volume, returns current state of device, id,level 0-100."""
path = "/airplay_devices/" + device_id + "/volume"
path = f"/airplay_devices/{device_id}/volume"
return self._request("PUT", path, {"level": level})


Expand Down Expand Up @@ -431,7 +431,7 @@ def update_state(self, state_hash):

if "name" in state_hash:
name = state_hash.get("name", "")
self.device_name = (name + " AirTunes Speaker").strip()
self.device_name = f"{name} AirTunes Speaker".strip()

if "kind" in state_hash:
self.kind = state_hash.get("kind", None)
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/kodi/media_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -963,7 +963,7 @@ async def async_find_album(self, album_name, artist_name=""):
@staticmethod
def _find(key_word, words):
key_word = key_word.split(" ")
patt = [re.compile("(^| )" + k + "( |$)", re.IGNORECASE) for k in key_word]
patt = [re.compile(f"(^| ){k}( |$)", re.IGNORECASE) for k in key_word]

out = [[i, 0] for i in range(len(words))]
for i in range(len(words)):
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/konnected/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -488,7 +488,7 @@ async def get(self, request: Request, device_id) -> Response:
device = data[CONF_DEVICES][device_id]
if not device:
return self.json_message(
"Device " + device_id + " not configured", status_code=HTTP_NOT_FOUND
f"Device {device_id} not configured", status_code=HTTP_NOT_FOUND
)

try:
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/life360/device_tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ def _err(self, key, err_msg):
msg = f"{key}: {err_msg}"
if _errs >= self._error_threshold:
if _errs == self._max_errs:
msg = "Suppressing further errors until OK: " + msg
msg = f"Suppressing further errors until OK: {msg}"
_LOGGER.error(msg)
elif _errs >= self._warning_threshold:
_LOGGER.warning(msg)
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/lifx/light.py
Original file line number Diff line number Diff line change
Expand Up @@ -562,7 +562,7 @@ def effect(self):
"""Return the name of the currently running effect."""
effect = self.effects_conductor.effect(self.bulb)
if effect:
return "lifx_effect_" + effect.name
return f"lifx_effect_{effect.name}"
return None

async def update_hass(self, now=None):
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/netatmo/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,9 +155,9 @@ def __init__(
else:
self._name = camera_name
if module_name:
self._name += " / " + module_name
self._name += f" / {module_name}"
self._sensor_name = sensor
self._name += " " + sensor
self._name += f" {sensor}"
self._cameratype = camera_type
self._state = None

Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/netatmo/camera.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def __init__(self, data, camera_name, home, camera_type, verify_ssl, quality):
self._camera_name = camera_name
self._home = home
if home:
self._name = home + " / " + camera_name
self._name = f"{home} / {camera_name}"
else:
self._name = camera_name
self._cameratype = camera_type
Expand Down Expand Up @@ -383,7 +383,7 @@ def _set_light_mode(self, mode):
"""Set light mode ('auto', 'on', 'off')."""
if self.model == "Presence":
try:
config = '{"mode":"' + mode + '"}'
config = f'{{"mode":"{mode}"}}'
if self._localurl:
requests.get(
f"{self._localurl}/command/floodlight_set_config?config={config}",
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/netgear/device_tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ def scan_devices(self):
self.tracked_accesspoints
and dev.conn_ap_mac in self.tracked_accesspoints
):
devices.append(dev.mac + "_" + dev.conn_ap_mac)
devices.append(f"{dev.mac}_{dev.conn_ap_mac}")

return devices

Expand Down Expand Up @@ -144,7 +144,7 @@ def get_device_name(self, device):
ap_name = dev.name
break

return name + " on " + ap_name
return f"{name} on {ap_name}"

return name

Expand Down
12 changes: 5 additions & 7 deletions homeassistant/components/octoprint/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def ensure_valid_path(value):
"""Validate the path, ensuring it starts and ends with a /."""
vol.Schema(cv.string)(value)
if value[0] != "/":
value = "/" + value
value = f"/{value}"
if value[-1] != "/":
value += "/"
return value
Expand Down Expand Up @@ -189,7 +189,7 @@ def get_tools(self):
tools = []
if self.number_of_tools > 0:
for tool_number in range(0, self.number_of_tools):
tools.append("tool" + str(tool_number))
tools.append(f"tool{tool_number!s}")
if self.bed:
tools.append("bed")
if not self.bed and self.number_of_tools == 0:
Expand Down Expand Up @@ -231,18 +231,16 @@ def get(self, endpoint):
self.printer_error_logged = False
return response.json()
except Exception as conn_exc: # pylint: disable=broad-except
log_string = "Failed to update OctoPrint status. " + " Error: %s" % (
conn_exc
)
log_string = "Failed to update OctoPrint status. Error: %s" % conn_exc
# Only log the first failure
if endpoint == "job":
log_string = "Endpoint: job " + log_string
log_string = f"Endpoint: job {log_string}"
if not self.job_error_logged:
_LOGGER.error(log_string)
self.job_error_logged = True
self.job_available = False
elif endpoint == "printer":
log_string = "Endpoint: printer " + log_string
log_string = f"Endpoint: printer {log_string}"
if not self.printer_error_logged:
_LOGGER.error(log_string)
self.printer_error_logged = True
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/onewire/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
# We have a raw GPIO ow sensor on a Pi
elif base_dir == DEFAULT_MOUNT_DIR:
for device_family in DEVICE_SENSORS:
for device_folder in glob(os.path.join(base_dir, device_family + "[.-]*")):
for device_folder in glob(os.path.join(base_dir, f"{device_family}[.-]*")):
sensor_id = os.path.split(device_folder)[1]
device_file = os.path.join(device_folder, "w1_slave")
devs.append(
Expand Down
18 changes: 9 additions & 9 deletions homeassistant/components/plant/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,15 +44,15 @@
# to have a separate literal for it to avoid confusion.
ATTR_DICT_OF_UNITS_OF_MEASUREMENT = "unit_of_measurement_dict"

CONF_MIN_BATTERY_LEVEL = "min_" + READING_BATTERY
CONF_MIN_TEMPERATURE = "min_" + READING_TEMPERATURE
CONF_MAX_TEMPERATURE = "max_" + READING_TEMPERATURE
CONF_MIN_MOISTURE = "min_" + READING_MOISTURE
CONF_MAX_MOISTURE = "max_" + READING_MOISTURE
CONF_MIN_CONDUCTIVITY = "min_" + READING_CONDUCTIVITY
CONF_MAX_CONDUCTIVITY = "max_" + READING_CONDUCTIVITY
CONF_MIN_BRIGHTNESS = "min_" + READING_BRIGHTNESS
CONF_MAX_BRIGHTNESS = "max_" + READING_BRIGHTNESS
CONF_MIN_BATTERY_LEVEL = f"min_{READING_BATTERY}"
CONF_MIN_TEMPERATURE = f"min_{READING_TEMPERATURE}"
CONF_MAX_TEMPERATURE = f"max_{READING_TEMPERATURE}"
CONF_MIN_MOISTURE = f"min_{READING_MOISTURE}"
CONF_MAX_MOISTURE = f"max_{READING_MOISTURE}"
CONF_MIN_CONDUCTIVITY = f"min_{READING_CONDUCTIVITY}"
CONF_MAX_CONDUCTIVITY = f"max_{READING_CONDUCTIVITY}"
CONF_MIN_BRIGHTNESS = f"min_{READING_BRIGHTNESS}"
CONF_MAX_BRIGHTNESS = f"max_{READING_BRIGHTNESS}"
CONF_CHECK_DAYS = "check_days"

CONF_SENSOR_BATTERY_LEVEL = READING_BATTERY
Expand Down
Loading

0 comments on commit fa4fa30

Please sign in to comment.