Use literal string interpolation in integrations E-G (f-strings) (#26379)

This commit is contained in:
Franck Nijhof 2019-09-03 17:10:56 +02:00 committed by Pascal Vizeli
parent 6a24d893c8
commit fa79ef1220
45 changed files with 87 additions and 92 deletions

View file

@ -106,7 +106,7 @@ class EBoxSensor(Entity):
@property @property
def name(self): def name(self):
"""Return the name of the sensor.""" """Return the name of the sensor."""
return "{} {}".format(self.client_name, self._name) return f"{self.client_name} {self._name}"
@property @property
def state(self): def state(self):

View file

@ -44,7 +44,7 @@ class EbusdSensor(Entity):
@property @property
def name(self): def name(self):
"""Return the name of the sensor.""" """Return the name of the sensor."""
return "{} {}".format(self._client_name, self._name) return f"{self._client_name} {self._name}"
@property @property
def state(self): def state(self):

View file

@ -123,7 +123,7 @@ class EcobeeWeather(WeatherEntity):
if self.weather: if self.weather:
station = self.weather.get("weatherStation", "UNKNOWN") station = self.weather.get("weatherStation", "UNKNOWN")
time = self.weather.get("timestamp", "UNKNOWN") time = self.weather.get("timestamp", "UNKNOWN")
return "Ecobee weather provided by {} at {}".format(station, time) return f"Ecobee weather provided by {station} at {time}"
return None return None
@property @property

View file

@ -99,7 +99,7 @@ class EfergySensor(Entity):
"""Initialize the sensor.""" """Initialize the sensor."""
self.sid = sid self.sid = sid
if sid: if sid:
self._name = "efergy_{}".format(sid) self._name = f"efergy_{sid}"
else: else:
self._name = SENSOR_TYPES[sensor_type][0] self._name = SENSOR_TYPES[sensor_type][0]
self.type = sensor_type self.type = sensor_type
@ -109,7 +109,7 @@ class EfergySensor(Entity):
self.period = period self.period = period
self.currency = currency self.currency = currency
if self.type == "cost": if self.type == "cost":
self._unit_of_measurement = "{}/{}".format(self.currency, self.period) self._unit_of_measurement = f"{self.currency}/{self.period}"
else: else:
self._unit_of_measurement = SENSOR_TYPES[sensor_type][1] self._unit_of_measurement = SENSOR_TYPES[sensor_type][1]
@ -132,7 +132,7 @@ class EfergySensor(Entity):
"""Get the Efergy monitor data from the web service.""" """Get the Efergy monitor data from the web service."""
try: try:
if self.type == "instant_readings": if self.type == "instant_readings":
url_string = "{}getInstant?token={}".format(_RESOURCE, self.app_token) url_string = f"{_RESOURCE}getInstant?token={self.app_token}"
response = requests.get(url_string, timeout=10) response = requests.get(url_string, timeout=10)
self._state = response.json()["reading"] self._state = response.json()["reading"]
elif self.type == "amount": elif self.type == "amount":
@ -142,7 +142,7 @@ class EfergySensor(Entity):
response = requests.get(url_string, timeout=10) response = requests.get(url_string, timeout=10)
self._state = response.json()["sum"] self._state = response.json()["sum"]
elif self.type == "budget": elif self.type == "budget":
url_string = "{}getBudget?token={}".format(_RESOURCE, self.app_token) url_string = f"{_RESOURCE}getBudget?token={self.app_token}"
response = requests.get(url_string, timeout=10) response = requests.get(url_string, timeout=10)
self._state = response.json()["status"] self._state = response.json()["status"]
elif self.type == "cost": elif self.type == "cost":

View file

@ -141,8 +141,8 @@ async def async_setup(hass, config):
for user in eight.users: for user in eight.users:
obj = eight.users[user] obj = eight.users[user]
for sensor in SENSORS: for sensor in SENSORS:
sensors.append("{}_{}".format(obj.side, sensor)) sensors.append(f"{obj.side}_{sensor}")
binary_sensors.append("{}_presence".format(obj.side)) binary_sensors.append(f"{obj.side}_presence")
sensors.append("room_temp") sensors.append("room_temp")
else: else:
# No users, cannot continue # No users, cannot continue

View file

@ -34,7 +34,7 @@ class EightHeatSensor(EightSleepHeatEntity, BinarySensorDevice):
self._sensor = sensor self._sensor = sensor
self._mapped_name = NAME_MAP.get(self._sensor, self._sensor) self._mapped_name = NAME_MAP.get(self._sensor, self._sensor)
self._name = "{} {}".format(name, self._mapped_name) self._name = f"{name} {self._mapped_name}"
self._state = None self._state = None
self._side = self._sensor.split("_")[0] self._side = self._sensor.split("_")[0]

View file

@ -68,7 +68,7 @@ class EightHeatSensor(EightSleepHeatEntity):
self._sensor = sensor self._sensor = sensor
self._mapped_name = NAME_MAP.get(self._sensor, self._sensor) self._mapped_name = NAME_MAP.get(self._sensor, self._sensor)
self._name = "{} {}".format(name, self._mapped_name) self._name = f"{name} {self._mapped_name}"
self._state = None self._state = None
self._side = self._sensor.split("_")[0] self._side = self._sensor.split("_")[0]
@ -122,7 +122,7 @@ class EightUserSensor(EightSleepUserEntity):
self._sensor = sensor self._sensor = sensor
self._sensor_root = self._sensor.split("_", 1)[1] self._sensor_root = self._sensor.split("_", 1)[1]
self._mapped_name = NAME_MAP.get(self._sensor, self._sensor) self._mapped_name = NAME_MAP.get(self._sensor, self._sensor)
self._name = "{} {}".format(name, self._mapped_name) self._name = f"{name} {self._mapped_name}"
self._state = None self._state = None
self._attr = None self._attr = None
self._units = units self._units = units
@ -261,7 +261,7 @@ class EightRoomSensor(EightSleepUserEntity):
self._sensor = sensor self._sensor = sensor
self._mapped_name = NAME_MAP.get(self._sensor, self._sensor) self._mapped_name = NAME_MAP.get(self._sensor, self._sensor)
self._name = "{} {}".format(name, self._mapped_name) self._name = f"{name} {self._mapped_name}"
self._state = None self._state = None
self._attr = None self._attr = None
self._units = units self._units = units

View file

@ -146,7 +146,7 @@ async def async_setup(hass: HomeAssistant, hass_config: ConfigType) -> bool:
def _included(ranges, set_to, values): def _included(ranges, set_to, values):
for rng in ranges: for rng in ranges:
if not rng[0] <= rng[1] <= len(values): if not rng[0] <= rng[1] <= len(values):
raise vol.Invalid("Invalid range {}".format(rng)) raise vol.Invalid(f"Invalid range {rng}")
values[rng[0] - 1 : rng[1]] = [set_to] * (rng[1] - rng[0] + 1) values[rng[0] - 1 : rng[1]] = [set_to] * (rng[1] - rng[0] + 1)
for index, conf in enumerate(hass_config[DOMAIN]): for index, conf in enumerate(hass_config[DOMAIN]):
@ -250,7 +250,7 @@ class ElkEntity(Entity):
# we could have used elkm1__foo_bar for the latter, but that # we could have used elkm1__foo_bar for the latter, but that
# would have been a breaking change # would have been a breaking change
if self._prefix != "": if self._prefix != "":
uid_start = "elkm1m_{prefix}".format(prefix=self._prefix) uid_start = f"elkm1m_{self._prefix}"
else: else:
uid_start = "elkm1" uid_start = "elkm1"
self._unique_id = "{uid_start}_{name}".format( self._unique_id = "{uid_start}_{name}".format(
@ -260,7 +260,7 @@ class ElkEntity(Entity):
@property @property
def name(self): def name(self):
"""Name of the element.""" """Name of the element."""
return "{p}{n}".format(p=self._prefix, n=self._element.name) return f"{self._prefix}{self._element.name}"
@property @property
def unique_id(self): def unique_id(self):

View file

@ -59,7 +59,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
def _dispatch(signal, entity_ids, *args): def _dispatch(signal, entity_ids, *args):
for entity_id in entity_ids: for entity_id in entity_ids:
async_dispatcher_send(hass, "{}_{}".format(signal, entity_id), *args) async_dispatcher_send(hass, f"{signal}_{entity_id}", *args)
def _arm_service(service): def _arm_service(service):
entity_ids = service.data.get(ATTR_ENTITY_ID, []) entity_ids = service.data.get(ATTR_ENTITY_ID, [])
@ -117,13 +117,11 @@ class ElkArea(ElkEntity, alarm.AlarmControlPanel):
for keypad in self._elk.keypads: for keypad in self._elk.keypads:
keypad.add_callback(self._watch_keypad) keypad.add_callback(self._watch_keypad)
async_dispatcher_connect( async_dispatcher_connect(
self.hass, self.hass, f"{SIGNAL_ARM_ENTITY}_{self.entity_id}", self._arm_service
"{}_{}".format(SIGNAL_ARM_ENTITY, self.entity_id),
self._arm_service,
) )
async_dispatcher_connect( async_dispatcher_connect(
self.hass, self.hass,
"{}_{}".format(SIGNAL_DISPLAY_MESSAGE, self.entity_id), f"{SIGNAL_DISPLAY_MESSAGE}_{self.entity_id}",
self._display_message, self._display_message,
) )

View file

@ -209,8 +209,7 @@ class EmbyDevice(MediaPlayerDevice):
def name(self): def name(self):
"""Return the name of the device.""" """Return the name of the device."""
return ( return (
"Emby - {} - {}".format(self.device.client, self.device.name) f"Emby - {self.device.client} - {self.device.name}" or DEVICE_DEFAULT_NAME
or DEVICE_DEFAULT_NAME
) )
@property @property

View file

@ -135,7 +135,7 @@ class EmonCmsSensor(Entity):
id_for_name = "" if str(sensorid) == "1" else sensorid id_for_name = "" if str(sensorid) == "1" else sensorid
# Use the feed name assigned in EmonCMS or fall back to the feed ID # Use the feed name assigned in EmonCMS or fall back to the feed ID
feed_name = elem.get("name") or "Feed {}".format(elem["id"]) feed_name = elem.get("name") or "Feed {}".format(elem["id"])
self._name = "EmonCMS{} {}".format(id_for_name, feed_name) self._name = f"EmonCMS{id_for_name} {feed_name}"
else: else:
self._name = name self._name = name
self._identifier = get_id( self._identifier = get_id(
@ -225,7 +225,7 @@ class EmonCmsData:
def __init__(self, hass, url, apikey, interval): def __init__(self, hass, url, apikey, interval):
"""Initialize the data object.""" """Initialize the data object."""
self._apikey = apikey self._apikey = apikey
self._url = "{}/feed/list.json".format(url) self._url = f"{url}/feed/list.json"
self._interval = interval self._interval = interval
self._hass = hass self._hass = hass
self.data = None self.data = None

View file

@ -47,7 +47,7 @@ def setup(hass, config):
def send_data(url, apikey, node, payload): def send_data(url, apikey, node, payload):
"""Send payload data to Emoncms.""" """Send payload data to Emoncms."""
try: try:
fullurl = "{}/input/post.json".format(url) fullurl = f"{url}/input/post.json"
data = {"apikey": apikey, "data": payload} data = {"apikey": apikey, "data": payload}
parameters = {"node": node} parameters = {"node": node}
req = requests.post( req = requests.post(
@ -83,7 +83,7 @@ def setup(hass, config):
if payload_dict: if payload_dict:
payload = "{%s}" % ",".join( payload = "{%s}" % ",".join(
"{}:{}".format(key, val) for key, val in payload_dict.items() f"{key}:{val}" for key, val in payload_dict.items()
) )
send_data( send_data(

View file

@ -590,5 +590,5 @@ def entity_to_json(config, entity, state):
def create_hue_success_response(entity_id, attr, value): def create_hue_success_response(entity_id, attr, value):
"""Create a success response for an attribute set on a light.""" """Create a success response for an attribute set on a light."""
success_key = "/lights/{}/state/{}".format(entity_id, attr) success_key = f"/lights/{entity_id}/state/{attr}"
return {"success": {success_key: value}} return {"success": {success_key: value}}

View file

@ -121,7 +121,7 @@ async def async_setup_platform(hass, config, async_add_entities, discovery_info=
try: try:
given_name = "{} {}".format(name, data.get_stop_info(place).name) given_name = "{} {}".format(name, data.get_stop_info(place).name)
except KeyError: except KeyError:
given_name = "{} {}".format(name, place) given_name = f"{name} {place}"
entities.append( entities.append(
EnturPublicTransportSensor(proxy, given_name, place, show_on_map) EnturPublicTransportSensor(proxy, given_name, place, show_on_map)

View file

@ -80,7 +80,7 @@ async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool
host, host,
port, port,
password, password,
client_info="Home Assistant {}".format(const.__version__), client_info=f"Home Assistant {const.__version__}",
) )
# Store client in per-config-entry hass.data # Store client in per-config-entry hass.data
@ -254,7 +254,7 @@ async def _async_setup_device_registry(
"""Set up device registry feature for a particular config entry.""" """Set up device registry feature for a particular config entry."""
sw_version = device_info.esphome_version sw_version = device_info.esphome_version
if device_info.compilation_time: if device_info.compilation_time:
sw_version += " ({})".format(device_info.compilation_time) sw_version += f" ({device_info.compilation_time})"
device_registry = await dr.async_get_registry(hass) device_registry = await dr.async_get_registry(hass)
device_registry.async_get_or_create( device_registry.async_get_or_create(
config_entry_id=entry.entry_id, config_entry_id=entry.entry_id,
@ -269,7 +269,7 @@ async def _async_setup_device_registry(
async def _register_service( async def _register_service(
hass: HomeAssistantType, entry_data: RuntimeEntryData, service: UserService hass: HomeAssistantType, entry_data: RuntimeEntryData, service: UserService
): ):
service_name = "{}_{}".format(entry_data.device_info.name, service.name) service_name = f"{entry_data.device_info.name}_{service.name}"
schema = {} schema = {}
for arg in service.args: for arg in service.args:
schema[vol.Required(arg.name)] = { schema[vol.Required(arg.name)] = {
@ -315,7 +315,7 @@ async def _setup_services(
entry_data.services = {serv.key: serv for serv in services} entry_data.services = {serv.key: serv for serv in services}
for service in to_unregister: for service in to_unregister:
service_name = "{}_{}".format(entry_data.device_info.name, service.name) service_name = f"{entry_data.device_info.name}_{service.name}"
hass.services.async_remove(DOMAIN, service_name) hass.services.async_remove(DOMAIN, service_name)
for service in to_register: for service in to_register:

View file

@ -95,7 +95,7 @@ class EssentMeter(Entity):
@property @property
def name(self): def name(self):
"""Return the name of the sensor.""" """Return the name of the sensor."""
return "Essent {} ({})".format(self._type, self._tariff) return f"Essent {self._type} ({self._tariff})"
@property @property
def state(self): def state(self):

View file

@ -87,7 +87,7 @@ class EverLightsLight(Light):
@property @property
def unique_id(self) -> str: def unique_id(self) -> str:
"""Return a unique ID.""" """Return a unique ID."""
return "{}-{}".format(self._mac, self._channel) return f"{self._mac}-{self._channel}"
@property @property
def available(self) -> bool: def available(self) -> bool:
@ -102,7 +102,7 @@ class EverLightsLight(Light):
@property @property
def is_on(self): def is_on(self):
"""Return true if device is on.""" """Return true if device is on."""
return self._status["ch{}Active".format(self._channel)] == 1 return self._status[f"ch{self._channel}Active"] == 1
@property @property
def brightness(self): def brightness(self):

View file

@ -168,7 +168,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
port = config[CONF_PORT] port = config[CONF_PORT]
username = config.get(CONF_USERNAME) username = config.get(CONF_USERNAME)
password = config.get(CONF_PASSWORD) password = config.get(CONF_PASSWORD)
url_health = "http://{}:{}/healthz".format(ip_address, port) url_health = f"http://{ip_address}:{port}/healthz"
hostname = check_box_health(url_health, username, password) hostname = check_box_health(url_health, username, password)
if hostname is None: if hostname is None:
return return
@ -214,8 +214,8 @@ class FaceClassifyEntity(ImageProcessingFaceEntity):
): ):
"""Init with the API key and model id.""" """Init with the API key and model id."""
super().__init__() super().__init__()
self._url_check = "http://{}:{}/{}/check".format(ip_address, port, CLASSIFIER) self._url_check = f"http://{ip_address}:{port}/{CLASSIFIER}/check"
self._url_teach = "http://{}:{}/{}/teach".format(ip_address, port, CLASSIFIER) self._url_teach = f"http://{ip_address}:{port}/{CLASSIFIER}/teach"
self._username = username self._username = username
self._password = password self._password = password
self._hostname = hostname self._hostname = hostname
@ -224,7 +224,7 @@ class FaceClassifyEntity(ImageProcessingFaceEntity):
self._name = name self._name = name
else: else:
camera_name = split_entity_id(camera_entity)[1] camera_name = split_entity_id(camera_entity)[1]
self._name = "{} {}".format(CLASSIFIER, camera_name) self._name = f"{CLASSIFIER} {camera_name}"
self._matched = {} self._matched = {}
def process_image(self, image): def process_image(self, image):

View file

@ -57,7 +57,7 @@ class BanSensor(Entity):
def __init__(self, name, jail, log_parser): def __init__(self, name, jail, log_parser):
"""Initialize the sensor.""" """Initialize the sensor."""
self._name = "{} {}".format(name, jail) self._name = f"{name} {jail}"
self.jail = jail self.jail = jail
self.ban_dict = {STATE_CURRENT_BANS: [], STATE_ALL_BANS: []} self.ban_dict = {STATE_CURRENT_BANS: [], STATE_ALL_BANS: []}
self.last_ban = None self.last_ban = None

View file

@ -11,7 +11,7 @@ from homeassistant.helpers.dispatcher import dispatcher_send
from homeassistant.helpers.event import async_track_time_interval from homeassistant.helpers.event import async_track_time_interval
DOMAIN = "fastdotcom" DOMAIN = "fastdotcom"
DATA_UPDATED = "{}_data_updated".format(DOMAIN) DATA_UPDATED = f"{DOMAIN}_data_updated"
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)

View file

@ -44,7 +44,7 @@ def setup(hass, config):
urls = config.get(DOMAIN)[CONF_URLS] urls = config.get(DOMAIN)[CONF_URLS]
scan_interval = config.get(DOMAIN).get(CONF_SCAN_INTERVAL) scan_interval = config.get(DOMAIN).get(CONF_SCAN_INTERVAL)
max_entries = config.get(DOMAIN).get(CONF_MAX_ENTRIES) max_entries = config.get(DOMAIN).get(CONF_MAX_ENTRIES)
data_file = hass.config.path("{}.pickle".format(DOMAIN)) data_file = hass.config.path(f"{DOMAIN}.pickle")
storage = StoredData(data_file) storage = StoredData(data_file)
feeds = [ feeds = [
FeedManager(url, scan_interval, max_entries, hass, storage) for url in urls FeedManager(url, scan_interval, max_entries, hass, storage) for url in urls

View file

@ -247,11 +247,11 @@ class FibaroController:
else: else:
room_name = self._room_map[device.roomID].name room_name = self._room_map[device.roomID].name
device.room_name = room_name device.room_name = room_name
device.friendly_name = "{} {}".format(room_name, device.name) device.friendly_name = f"{room_name} {device.name}"
device.ha_id = "scene_{}_{}_{}".format( device.ha_id = "scene_{}_{}_{}".format(
slugify(room_name), slugify(device.name), device.id slugify(room_name), slugify(device.name), device.id
) )
device.unique_id_str = "{}.scene.{}".format(self.hub_serial, device.id) device.unique_id_str = f"{self.hub_serial}.scene.{device.id}"
self._scene_map[device.id] = device self._scene_map[device.id] = device
self.fibaro_devices["scene"].append(device) self.fibaro_devices["scene"].append(device)
@ -287,7 +287,7 @@ class FibaroController:
device.mapped_type = None device.mapped_type = None
dtype = device.mapped_type dtype = device.mapped_type
if dtype: if dtype:
device.unique_id_str = "{}.{}".format(self.hub_serial, device.id) device.unique_id_str = f"{self.hub_serial}.{device.id}"
self._device_map[device.id] = device self._device_map[device.id] = device
if dtype != "climate": if dtype != "climate":
self.fibaro_devices[dtype].append(device) self.fibaro_devices[dtype].append(device)
@ -414,7 +414,7 @@ class FibaroDevice(Entity):
green = int(max(0, min(255, green))) green = int(max(0, min(255, green)))
blue = int(max(0, min(255, blue))) blue = int(max(0, min(255, blue)))
white = int(max(0, min(255, white))) white = int(max(0, min(255, white)))
color_str = "{},{},{},{}".format(red, green, blue, white) color_str = f"{red},{green},{blue},{white}"
self.fibaro_device.properties.color = color_str self.fibaro_device.properties.color = color_str
self.action("setColor", str(red), str(green), str(blue), str(white)) self.action("setColor", str(red), str(green), str(blue), str(white))

View file

@ -115,7 +115,7 @@ class FibaroThermostat(FibaroDevice, ClimateDevice):
self._op_mode_device = None self._op_mode_device = None
self._fan_mode_device = None self._fan_mode_device = None
self._support_flags = 0 self._support_flags = 0
self.entity_id = "climate.{}".format(self.ha_id) self.entity_id = f"climate.{self.ha_id}"
self._hvac_support = [] self._hvac_support = []
self._preset_support = [] self._preset_support = []
self._fan_support = [] self._fan_support = []

View file

@ -108,7 +108,7 @@ class FidoSensor(Entity):
@property @property
def name(self): def name(self):
"""Return the name of the sensor.""" """Return the name of the sensor."""
return "{} {} {}".format(self.client_name, self._number, self._name) return f"{self.client_name} {self._number} {self._name}"
@property @property
def state(self): def state(self):

View file

@ -57,5 +57,5 @@ class FileNotificationService(BaseNotificationService):
if self.add_timestamp: if self.add_timestamp:
text = "{} {}\n".format(dt_util.utcnow().isoformat(), message) text = "{} {}\n".format(dt_util.utcnow().isoformat(), message)
else: else:
text = "{}\n".format(message) text = f"{message}\n"
file.write(text) file.write(text)

View file

@ -332,7 +332,7 @@ class FilterState:
def __repr__(self): def __repr__(self):
"""Return timestamp and state as the representation of FilterState.""" """Return timestamp and state as the representation of FilterState."""
return "{} : {}".format(self.timestamp, self.state) return f"{self.timestamp} : {self.state}"
class Filter: class Filter:

View file

@ -77,7 +77,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
account_name = account_config.get(account.iban) account_name = account_config.get(account.iban)
if not account_name: if not account_name:
account_name = "{} - {}".format(fints_name, account.iban) account_name = f"{fints_name} - {account.iban}"
accounts.append(FinTsAccount(client, account, account_name)) accounts.append(FinTsAccount(client, account, account_name))
_LOGGER.debug("Creating account %s for bank %s", account.iban, fints_name) _LOGGER.debug("Creating account %s for bank %s", account.iban, fints_name)
@ -90,7 +90,7 @@ def setup_platform(hass, config, add_entities, discovery_info=None):
account_name = holdings_config.get(account.accountnumber) account_name = holdings_config.get(account.accountnumber)
if not account_name: if not account_name:
account_name = "{} - {}".format(fints_name, account.accountnumber) account_name = f"{fints_name} - {account.accountnumber}"
accounts.append(FinTsHoldingsAccount(client, account, account_name)) accounts.append(FinTsHoldingsAccount(client, account, account_name))
_LOGGER.debug( _LOGGER.debug(
"Creating holdings %s for bank %s", account.accountnumber, fints_name "Creating holdings %s for bank %s", account.accountnumber, fints_name
@ -265,11 +265,11 @@ class FinTsHoldingsAccount(Entity):
if self._client.name: if self._client.name:
attributes[ATTR_BANK] = self._client.name attributes[ATTR_BANK] = self._client.name
for holding in self._holdings: for holding in self._holdings:
total_name = "{} total".format(holding.name) total_name = f"{holding.name} total"
attributes[total_name] = holding.total_value attributes[total_name] = holding.total_value
pieces_name = "{} pieces".format(holding.name) pieces_name = f"{holding.name} pieces"
attributes[pieces_name] = holding.pieces attributes[pieces_name] = holding.pieces
price_name = "{} price".format(holding.name) price_name = f"{holding.name} price"
attributes[price_name] = holding.market_value attributes[price_name] = holding.market_value
return attributes return attributes

View file

@ -167,7 +167,7 @@ def request_app_setup(hass, config, add_entities, config_path, discovery_info=No
else: else:
setup_platform(hass, config, add_entities, discovery_info) setup_platform(hass, config, add_entities, discovery_info)
start_url = "{}{}".format(hass.config.api.base_url, FITBIT_AUTH_CALLBACK_PATH) start_url = f"{hass.config.api.base_url}{FITBIT_AUTH_CALLBACK_PATH}"
description = """Please create a Fitbit developer app at description = """Please create a Fitbit developer app at
https://dev.fitbit.com/apps/new. https://dev.fitbit.com/apps/new.
@ -204,9 +204,9 @@ def request_oauth_completion(hass):
def fitbit_configuration_callback(callback_data): def fitbit_configuration_callback(callback_data):
"""Handle configuration updates.""" """Handle configuration updates."""
start_url = "{}{}".format(hass.config.api.base_url, FITBIT_AUTH_START) start_url = f"{hass.config.api.base_url}{FITBIT_AUTH_START}"
description = "Please authorize Fitbit by visiting {}".format(start_url) description = f"Please authorize Fitbit by visiting {start_url}"
_CONFIGURING["fitbit"] = configurator.request_config( _CONFIGURING["fitbit"] = configurator.request_config(
"Fitbit", "Fitbit",
@ -498,7 +498,7 @@ class FitbitSensor(Entity):
hours -= 12 hours -= 12
elif hours == 0: elif hours == 0:
hours = 12 hours = 12
self._state = "{}:{:02d} {}".format(hours, minutes, setting) self._state = f"{hours}:{minutes:02d} {setting}"
else: else:
self._state = raw_state self._state = raw_state
else: else:

View file

@ -20,7 +20,7 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({vol.Required(CONF_ACCESS_TOKEN): cv.st
async def get_service(hass, config, discovery_info=None): async def get_service(hass, config, discovery_info=None):
"""Get the Flock notification service.""" """Get the Flock notification service."""
access_token = config.get(CONF_ACCESS_TOKEN) access_token = config.get(CONF_ACCESS_TOKEN)
url = "{}{}".format(_RESOURCE, access_token) url = f"{_RESOURCE}{access_token}"
session = async_get_clientsession(hass) session = async_get_clientsession(hass)
return FlockNotificationService(url, session) return FlockNotificationService(url, session)

View file

@ -143,7 +143,7 @@ class FluNearYouSensor(Entity):
@property @property
def unique_id(self): def unique_id(self):
"""Return a unique, HASS-friendly identifier for this entity.""" """Return a unique, HASS-friendly identifier for this entity."""
return "{0},{1}_{2}".format(self.fny.latitude, self.fny.longitude, self._kind) return f"{self.fny.latitude},{self.fny.longitude}_{self._kind}"
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):

View file

@ -117,7 +117,7 @@ class FoobotSensor(Entity):
@property @property
def unique_id(self): def unique_id(self):
"""Return the unique id of this entity.""" """Return the unique id of this entity."""
return "{}_{}".format(self._uuid, self.type) return f"{self._uuid}_{self.type}"
@property @property
def unit_of_measurement(self): def unit_of_measurement(self):

View file

@ -95,7 +95,7 @@ class FritzDectSwitch(SwitchDevice):
attrs[ATTR_CURRENT_CONSUMPTION_UNIT] = "{}".format( attrs[ATTR_CURRENT_CONSUMPTION_UNIT] = "{}".format(
ATTR_CURRENT_CONSUMPTION_UNIT_VALUE ATTR_CURRENT_CONSUMPTION_UNIT_VALUE
) )
attrs[ATTR_TOTAL_CONSUMPTION] = "{:.3f}".format(self.data.total_consumption) attrs[ATTR_TOTAL_CONSUMPTION] = f"{self.data.total_consumption:.3f}"
attrs[ATTR_TOTAL_CONSUMPTION_UNIT] = "{}".format( attrs[ATTR_TOTAL_CONSUMPTION_UNIT] = "{}".format(
ATTR_TOTAL_CONSUMPTION_UNIT_VALUE ATTR_TOTAL_CONSUMPTION_UNIT_VALUE
) )
@ -104,7 +104,7 @@ class FritzDectSwitch(SwitchDevice):
attrs[ATTR_TEMPERATURE] = "{}".format( attrs[ATTR_TEMPERATURE] = "{}".format(
self.units.temperature(self.data.temperature, TEMP_CELSIUS) self.units.temperature(self.data.temperature, TEMP_CELSIUS)
) )
attrs[ATTR_TEMPERATURE_UNIT] = "{}".format(self.units.temperature_unit) attrs[ATTR_TEMPERATURE_UNIT] = f"{self.units.temperature_unit}"
return attrs return attrs
@property @property

View file

@ -177,7 +177,7 @@ class GaradgetCover(CoverDevice):
"username": self._username, "username": self._username,
"password": self._password, "password": self._password,
} }
url = "{}/oauth/token".format(self.particle_url) url = f"{self.particle_url}/oauth/token"
ret = requests.post(url, auth=("particle", "particle"), data=args, timeout=10) ret = requests.post(url, auth=("particle", "particle"), data=args, timeout=10)
try: try:
@ -187,7 +187,7 @@ class GaradgetCover(CoverDevice):
def remove_token(self): def remove_token(self):
"""Remove authorization token from API.""" """Remove authorization token from API."""
url = "{}/v1/access_tokens/{}".format(self.particle_url, self.access_token) url = f"{self.particle_url}/v1/access_tokens/{self.access_token}"
ret = requests.delete(url, auth=(self._username, self._password), timeout=10) ret = requests.delete(url, auth=(self._username, self._password), timeout=10)
return ret.text return ret.text
@ -266,6 +266,6 @@ class GaradgetCover(CoverDevice):
params = {"access_token": self.access_token} params = {"access_token": self.access_token}
if arg: if arg:
params["command"] = arg params["command"] = arg
url = "{}/v1/devices/{}/{}".format(self.particle_url, self.device_id, func) url = f"{self.particle_url}/v1/devices/{self.device_id}/{func}"
ret = requests.post(url, data=params, timeout=10) ret = requests.post(url, data=params, timeout=10)
return ret.json() return ret.json()

View file

@ -29,9 +29,9 @@ class GeniusBinarySensor(GeniusEntity, BinarySensorDevice):
self._device = device self._device = device
if device.type[:21] == "Dual Channel Receiver": if device.type[:21] == "Dual Channel Receiver":
self._name = "Dual Channel Receiver {}".format(device.id) self._name = f"Dual Channel Receiver {device.id}"
else: else:
self._name = "{} {}".format(device.type, device.id) self._name = f"{device.type} {device.id}"
@property @property
def is_on(self) -> bool: def is_on(self) -> bool:

View file

@ -34,7 +34,7 @@ class GeniusBattery(GeniusEntity):
super().__init__() super().__init__()
self._device = device self._device = device
self._name = "{} {}".format(device.type, device.id) self._name = f"{device.type} {device.id}"
@property @property
def icon(self) -> str: def icon(self) -> str:
@ -112,7 +112,7 @@ class GeniusIssue(GeniusEntity):
@property @property
def device_state_attributes(self) -> Dict[str, Any]: def device_state_attributes(self) -> Dict[str, Any]:
"""Return the device state attributes.""" """Return the device state attributes."""
return {"{}_list".format(self._level): self._issues} return {f"{self._level}_list": self._issues}
async def async_update(self) -> Awaitable[None]: async def async_update(self) -> Awaitable[None]:
"""Process the sensor's state data.""" """Process the sensor's state data."""

View file

@ -157,7 +157,7 @@ class GeoRssServiceSensor(Entity):
# And now compute the attributes from the filtered events. # And now compute the attributes from the filtered events.
matrix = {} matrix = {}
for entry in feed_entries: for entry in feed_entries:
matrix[entry.title] = "{:.0f}km".format(entry.distance_to_home) matrix[entry.title] = f"{entry.distance_to_home:.0f}km"
self._state_attributes = matrix self._state_attributes = matrix
elif status == georss_client.UPDATE_OK_NO_DATA: elif status == georss_client.UPDATE_OK_NO_DATA:
_LOGGER.debug("Update successful, but no data received from %s", self._feed) _LOGGER.debug("Update successful, but no data received from %s", self._feed)

View file

@ -50,7 +50,7 @@ BEACON_DEV_PREFIX = "beacon"
LOCATION_ENTRY = "1" LOCATION_ENTRY = "1"
LOCATION_EXIT = "0" LOCATION_EXIT = "0"
TRACKER_UPDATE = "{}_tracker_update".format(DOMAIN) TRACKER_UPDATE = f"{DOMAIN}_tracker_update"
def _address(value: str) -> str: def _address(value: str) -> str:
@ -131,7 +131,7 @@ def _set_location(hass, data, location_name):
data, data,
) )
return web.Response(text="Setting location for {}".format(device), status=HTTP_OK) return web.Response(text=f"Setting location for {device}", status=HTTP_OK)
async def async_setup_entry(hass, entry): async def async_setup_entry(hass, entry):

View file

@ -59,10 +59,10 @@ SERVICE_ADD_EVENT = "add_event"
DATA_INDEX = "google_calendars" DATA_INDEX = "google_calendars"
YAML_DEVICES = "{}_calendars.yaml".format(DOMAIN) YAML_DEVICES = f"{DOMAIN}_calendars.yaml"
SCOPES = "https://www.googleapis.com/auth/calendar" SCOPES = "https://www.googleapis.com/auth/calendar"
TOKEN_FILE = ".{}.token".format(DOMAIN) TOKEN_FILE = f".{DOMAIN}.token"
CONFIG_SCHEMA = vol.Schema( CONFIG_SCHEMA = vol.Schema(
{ {

View file

@ -26,9 +26,7 @@ class ChallengeNeeded(SmartHomeError):
def __init__(self, challenge_type): def __init__(self, challenge_type):
"""Initialize challenge needed error.""" """Initialize challenge needed error."""
super().__init__( super().__init__(ERR_CHALLENGE_NEEDED, f"Challenge needed: {challenge_type}")
ERR_CHALLENGE_NEEDED, "Challenge needed: {}".format(challenge_type)
)
self.challenge_type = challenge_type self.challenge_type = challenge_type
def to_response(self): def to_response(self):

View file

@ -212,7 +212,7 @@ class GoogleEntity:
if not executed: if not executed:
raise SmartHomeError( raise SmartHomeError(
ERR_FUNCTION_NOT_SUPPORTED, ERR_FUNCTION_NOT_SUPPORTED,
"Unable to execute {} for {}".format(command, self.state.entity_id), f"Unable to execute {command} for {self.state.entity_id}",
) )
@callback @callback

View file

@ -88,7 +88,7 @@ class GoogleWifiSensor(Entity):
@property @property
def name(self): def name(self):
"""Return the name of the sensor.""" """Return the name of the sensor."""
return "{}_{}".format(self._name, self._var_name) return f"{self._name}_{self._var_name}"
@property @property
def icon(self): def icon(self):
@ -125,7 +125,7 @@ class GoogleWifiAPI:
def __init__(self, host, conditions): def __init__(self, host, conditions):
"""Initialize the data object.""" """Initialize the data object."""
uri = "http://" uri = "http://"
resource = "{}{}{}".format(uri, host, ENDPOINT) resource = f"{uri}{host}{ENDPOINT}"
self._request = requests.Request("GET", resource).prepare() self._request = requests.Request("GET", resource).prepare()
self.raw_data = None self.raw_data = None
self.conditions = conditions self.conditions = conditions

View file

@ -142,7 +142,7 @@ def setup_gpmdp(hass, config, code, add_entities):
name = config.get(CONF_NAME) name = config.get(CONF_NAME)
host = config.get(CONF_HOST) host = config.get(CONF_HOST)
port = config.get(CONF_PORT) port = config.get(CONF_PORT)
url = "ws://{}:{}".format(host, port) url = f"ws://{host}:{port}"
if not code: if not code:
request_configuration(hass, config, url, add_entities) request_configuration(hass, config, url, add_entities)

View file

@ -29,7 +29,7 @@ from .const import (
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
TRACKER_UPDATE = "{}_tracker_update".format(DOMAIN) TRACKER_UPDATE = f"{DOMAIN}_tracker_update"
DEFAULT_ACCURACY = 200 DEFAULT_ACCURACY = 200
@ -90,7 +90,7 @@ async def handle_webhook(hass, webhook_id, request):
attrs, attrs,
) )
return web.Response(text="Setting location for {}".format(device), status=HTTP_OK) return web.Response(text=f"Setting location for {device}", status=HTTP_OK)
async def async_setup_entry(hass, entry): async def async_setup_entry(hass, entry):

View file

@ -139,9 +139,9 @@ def get_next_departure(
if include_tomorrow: if include_tomorrow:
limit = int(limit / 2 * 3) limit = int(limit / 2 * 3)
tomorrow_name = tomorrow.strftime("%A").lower() tomorrow_name = tomorrow.strftime("%A").lower()
tomorrow_select = "calendar.{} AS tomorrow,".format(tomorrow_name) tomorrow_select = f"calendar.{tomorrow_name} AS tomorrow,"
tomorrow_where = "OR calendar.{} = 1".format(tomorrow_name) tomorrow_where = f"OR calendar.{tomorrow_name} = 1"
tomorrow_order = "calendar.{} DESC,".format(tomorrow_name) tomorrow_order = f"calendar.{tomorrow_name} DESC,"
sql_query = """ sql_query = """
SELECT trip.trip_id, trip.route_id, SELECT trip.trip_id, trip.route_id,
@ -357,7 +357,7 @@ def setup_platform(
(gtfs_root, _) = os.path.splitext(data) (gtfs_root, _) = os.path.splitext(data)
sqlite_file = "{}.sqlite?check_same_thread=False".format(gtfs_root) sqlite_file = f"{gtfs_root}.sqlite?check_same_thread=False"
joined_path = os.path.join(gtfs_dir, sqlite_file) joined_path = os.path.join(gtfs_dir, sqlite_file)
gtfs = pygtfs.Schedule(joined_path) gtfs = pygtfs.Schedule(joined_path)
@ -673,7 +673,7 @@ class GTFSDepartureSensor(Entity):
continue continue
key = attr key = attr
if prefix and not key.startswith(prefix): if prefix and not key.startswith(prefix):
key = "{} {}".format(prefix, key) key = f"{prefix} {key}"
key = slugify(key) key = slugify(key)
self._attributes[key] = val self._attributes[key] = val

View file

@ -38,7 +38,7 @@ class GttSensor(Entity):
"""Initialize the Gtt sensor.""" """Initialize the Gtt sensor."""
self.data = GttData(stop, bus_name) self.data = GttData(stop, bus_name)
self._state = None self._state = None
self._name = "Stop {}".format(stop) self._name = f"Stop {stop}"
@property @property
def name(self): def name(self):