String formatting and max line length - Part 6 (#84525)

This commit is contained in:
Franck Nijhof 2022-12-24 13:19:51 +01:00 committed by GitHub
parent ac1359b3d8
commit 8819634b61
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
51 changed files with 238 additions and 102 deletions

View file

@ -660,8 +660,8 @@ def _apply_update( # noqa: C901
# Using LOCK=EXCLUSIVE to prevent the database from corrupting # Using LOCK=EXCLUSIVE to prevent the database from corrupting
# https://github.com/home-assistant/core/issues/56104 # https://github.com/home-assistant/core/issues/56104
text( text(
f"ALTER TABLE {table} CONVERT TO " f"ALTER TABLE {table} CONVERT TO CHARACTER SET utf8mb4"
"CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci, LOCK=EXCLUSIVE" " COLLATE utf8mb4_unicode_ci, LOCK=EXCLUSIVE"
) )
) )
elif new_version == 22: elif new_version == 22:

View file

@ -1008,7 +1008,10 @@ class BaseTelegramBotEntity:
if from_user in self.allowed_chat_ids or from_chat in self.allowed_chat_ids: if from_user in self.allowed_chat_ids or from_chat in self.allowed_chat_ids:
return True return True
_LOGGER.error( _LOGGER.error(
"Unauthorized update - neither user id %s nor chat id %s is in allowed chats: %s", (
"Unauthorized update - neither user id %s nor chat id %s is in allowed"
" chats: %s"
),
from_user, from_user,
from_chat, from_chat,
self.allowed_chat_ids, self.allowed_chat_ids,

View file

@ -92,7 +92,8 @@ async def async_validate_config(hass, config):
if not legacy_warn_printed: if not legacy_warn_printed:
legacy_warn_printed = True legacy_warn_printed = True
logging.getLogger(__name__).warning( logging.getLogger(__name__).warning(
"The entity definition format under template: differs from the platform " "The entity definition format under template: differs from the"
" platform "
"configuration format. See " "configuration format. See "
"https://www.home-assistant.io/integrations/template#configuration-for-trigger-based-template-sensors" "https://www.home-assistant.io/integrations/template#configuration-for-trigger-based-template-sensors"
) )

View file

@ -474,7 +474,10 @@ class LightTemplate(TemplateEntity, LightEntity):
if not isinstance(effect_list, list): if not isinstance(effect_list, list):
_LOGGER.error( _LOGGER.error(
"Received invalid effect list: %s for entity %s. Expected list of strings", (
"Received invalid effect list: %s for entity %s. Expected list of"
" strings"
),
effect_list, effect_list,
self.entity_id, self.entity_id,
) )
@ -545,7 +548,10 @@ class LightTemplate(TemplateEntity, LightEntity):
self._temperature = temperature self._temperature = temperature
else: else:
_LOGGER.error( _LOGGER.error(
"Received invalid color temperature : %s for entity %s. Expected: %s-%s", (
"Received invalid color temperature : %s for entity %s."
" Expected: %s-%s"
),
temperature, temperature,
self.entity_id, self.entity_id,
self.min_mireds, self.min_mireds,
@ -554,7 +560,10 @@ class LightTemplate(TemplateEntity, LightEntity):
self._temperature = None self._temperature = None
except ValueError: except ValueError:
_LOGGER.error( _LOGGER.error(
"Template must supply an integer temperature within the range for this light, or 'None'", (
"Template must supply an integer temperature within the range for"
" this light, or 'None'"
),
exc_info=True, exc_info=True,
) )
self._temperature = None self._temperature = None
@ -586,7 +595,10 @@ class LightTemplate(TemplateEntity, LightEntity):
self._color = (h_str, s_str) self._color = (h_str, s_str)
elif h_str is not None and s_str is not None: elif h_str is not None and s_str is not None:
_LOGGER.error( _LOGGER.error(
"Received invalid hs_color : (%s, %s) for entity %s. Expected: (0-360, 0-100)", (
"Received invalid hs_color : (%s, %s) for entity %s. Expected:"
" (0-360, 0-100)"
),
h_str, h_str,
s_str, s_str,
self.entity_id, self.entity_id,
@ -609,7 +621,10 @@ class LightTemplate(TemplateEntity, LightEntity):
self._max_mireds = int(render) self._max_mireds = int(render)
except ValueError: except ValueError:
_LOGGER.error( _LOGGER.error(
"Template must supply an integer temperature within the range for this light, or 'None'", (
"Template must supply an integer temperature within the range for"
" this light, or 'None'"
),
exc_info=True, exc_info=True,
) )
self._max_mireds = None self._max_mireds = None
@ -624,7 +639,10 @@ class LightTemplate(TemplateEntity, LightEntity):
self._min_mireds = int(render) self._min_mireds = int(render)
except ValueError: except ValueError:
_LOGGER.error( _LOGGER.error(
"Template must supply an integer temperature within the range for this light, or 'None'", (
"Template must supply an integer temperature within the range for"
" this light, or 'None'"
),
exc_info=True, exc_info=True,
) )
self._min_mireds = None self._min_mireds = None

View file

@ -99,8 +99,9 @@ def extra_validation_checks(val):
"""Run extra validation checks.""" """Run extra validation checks."""
if CONF_TRIGGER in val: if CONF_TRIGGER in val:
raise vol.Invalid( raise vol.Invalid(
"You can only add triggers to template entities if they are defined under `template:`. " "You can only add triggers to template entities if they are defined under"
"See the template documentation for more information: https://www.home-assistant.io/integrations/template/" " `template:`. See the template documentation for more information:"
" https://www.home-assistant.io/integrations/template/"
) )
if CONF_SENSORS not in val and SENSOR_DOMAIN not in val: if CONF_SENSORS not in val and SENSOR_DOMAIN not in val:

View file

@ -62,7 +62,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
) from ex ) from ex
except WallConnectorConnectionError as ex: except WallConnectorConnectionError as ex:
raise UpdateFailed( raise UpdateFailed(
f"Could not fetch data from Tesla WallConnector at {hostname}: Cannot connect" f"Could not fetch data from Tesla WallConnector at {hostname}: Cannot"
" connect"
) from ex ) from ex
except WallConnectorError as ex: except WallConnectorError as ex:
raise UpdateFailed( raise UpdateFailed(

View file

@ -65,7 +65,8 @@ async def _async_set_value(entity: TextEntity, service_call: ServiceCall) -> Non
value = service_call.data[ATTR_VALUE] value = service_call.data[ATTR_VALUE]
if len(value) < entity.min: if len(value) < entity.min:
raise ValueError( raise ValueError(
f"Value {value} for {entity.name} is too short (minimum length {entity.min})" f"Value {value} for {entity.name} is too short (minimum length"
f" {entity.min})"
) )
if len(value) > entity.max: if len(value) > entity.max:
raise ValueError( raise ValueError(

View file

@ -124,5 +124,6 @@ class TMBSensor(SensorEntity):
self._state = self._ibus_client.get_stop_forecast(self._stop, self._line) self._state = self._ibus_client.get_stop_forecast(self._stop, self._line)
except HTTPError: except HTTPError:
_LOGGER.error( _LOGGER.error(
"Unable to fetch data from TMB API. Please check your API keys are valid" "Unable to fetch data from TMB API. Please check your API keys are"
" valid"
) )

View file

@ -115,7 +115,9 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
} }
self._discovered_devices = await async_discover_devices(self.hass) self._discovered_devices = await async_discover_devices(self.hass)
devices_name = { devices_name = {
formatted_mac: f"{device.alias} {device.model} ({device.host}) {formatted_mac}" formatted_mac: (
f"{device.alias} {device.model} ({device.host}) {formatted_mac}"
)
for formatted_mac, device in self._discovered_devices.items() for formatted_mac, device in self._discovered_devices.items()
if formatted_mac not in configured_devices if formatted_mac not in configured_devices
} }

View file

@ -226,7 +226,10 @@ class TractiveClient:
except aiotractive.exceptions.TractiveError: except aiotractive.exceptions.TractiveError:
_LOGGER.debug( _LOGGER.debug(
"Tractive is not available. Internet connection is down? Sleeping %i seconds and retrying", (
"Tractive is not available. Internet connection is down?"
" Sleeping %i seconds and retrying"
),
RECONNECT_INTERVAL.total_seconds(), RECONNECT_INTERVAL.total_seconds(),
) )
self._last_hw_time = 0 self._last_hw_time = 0

View file

@ -25,7 +25,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
if "Invalid authentication" in error.args[0]: if "Invalid authentication" in error.args[0]:
raise ConfigEntryAuthFailed from error raise ConfigEntryAuthFailed from error
raise ConfigEntryNotReady( raise ConfigEntryNotReady(
f"Problem when trying station {entry.data[CONF_FROM]} to {entry.data[CONF_TO]}. Error: {error} " f"Problem when trying station {entry.data[CONF_FROM]} to"
f" {entry.data[CONF_TO]}. Error: {error} "
) from error ) from error
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = { hass.data.setdefault(DOMAIN, {})[entry.entry_id] = {

View file

@ -106,9 +106,7 @@ def setup_platform(
_LOGGER.error("Unable to connect to Travis CI service: %s", str(ex)) _LOGGER.error("Unable to connect to Travis CI service: %s", str(ex))
persistent_notification.create( persistent_notification.create(
hass, hass,
"Error: {}<br />" f"Error: {ex}<br />You will need to restart hass after fixing.",
"You will need to restart hass after fixing."
"".format(ex),
title=NOTIFICATION_TITLE, title=NOTIFICATION_TITLE,
notification_id=NOTIFICATION_ID, notification_id=NOTIFICATION_ID,
) )

View file

@ -158,7 +158,8 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
base_url = conf.get(CONF_BASE_URL) base_url = conf.get(CONF_BASE_URL)
if base_url is not None: if base_url is not None:
_LOGGER.warning( _LOGGER.warning(
"TTS base_url option is deprecated. Configure internal/external URL instead" "TTS base_url option is deprecated. Configure internal/external URL"
" instead"
) )
hass.data[BASE_URL_KEY] = base_url hass.data[BASE_URL_KEY] = base_url
@ -241,7 +242,9 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
# Register the service description # Register the service description
service_desc = { service_desc = {
CONF_NAME: f"Say a TTS message with {p_type}", CONF_NAME: f"Say a TTS message with {p_type}",
CONF_DESCRIPTION: f"Say something using text-to-speech on a media player with {p_type}.", CONF_DESCRIPTION: (
f"Say something using text-to-speech on a media player with {p_type}."
),
CONF_FIELDS: services_dict[SERVICE_SAY][CONF_FIELDS], CONF_FIELDS: services_dict[SERVICE_SAY][CONF_FIELDS],
} }
async_set_service_schema(hass, DOMAIN, service_name, service_desc) async_set_service_schema(hass, DOMAIN, service_name, service_desc)

View file

@ -341,7 +341,8 @@ class TuyaClimateEntity(TuyaEntity, ClimateEntity):
"""Set new target temperature.""" """Set new target temperature."""
if self._set_temperature is None: if self._set_temperature is None:
raise RuntimeError( raise RuntimeError(
"Cannot set target temperature, device doesn't provide methods to set it" "Cannot set target temperature, device doesn't provide methods to"
" set it"
) )
self._send_command( self._send_command(

View file

@ -58,8 +58,7 @@ def _refresh_on_access_denied(func):
return func(self, *args, **kwargs) return func(self, *args, **kwargs)
except PermissionError: except PermissionError:
_LOGGER.warning( _LOGGER.warning(
"Invalid session detected." "Invalid session detected. Trying to refresh session_id and re-run RPC"
" Trying to refresh session_id and re-run RPC"
) )
self.ubus.connect() self.ubus.connect()

View file

@ -48,7 +48,10 @@ DEVICES_WITH_ENTITIES = DEVICES_THAT_ADOPT | {ModelType.NVR}
DEVICES_FOR_SUBSCRIBE = DEVICES_WITH_ENTITIES | {ModelType.EVENT} DEVICES_FOR_SUBSCRIBE = DEVICES_WITH_ENTITIES | {ModelType.EVENT}
MIN_REQUIRED_PROTECT_V = Version("1.20.0") MIN_REQUIRED_PROTECT_V = Version("1.20.0")
OUTDATED_LOG_MESSAGE = "You are running v%s of UniFi Protect. Minimum required version is v%s. Please upgrade UniFi Protect and then retry" OUTDATED_LOG_MESSAGE = (
"You are running v%s of UniFi Protect. Minimum required version is v%s. Please"
" upgrade UniFi Protect and then retry"
)
TYPE_EMPTY_VALUE = "" TYPE_EMPTY_VALUE = ""

View file

@ -240,7 +240,8 @@ class ProtectData:
# alert user viewport needs restart so voice clients can get new options # alert user viewport needs restart so voice clients can get new options
elif len(self.api.bootstrap.viewers) > 0 and isinstance(obj, Liveview): elif len(self.api.bootstrap.viewers) > 0 and isinstance(obj, Liveview):
_LOGGER.warning( _LOGGER.warning(
"Liveviews updated. Restart Home Assistant to update Viewport select options" "Liveviews updated. Restart Home Assistant to update Viewport select"
" options"
) )
@callback @callback

View file

@ -146,7 +146,10 @@ async def async_migrate_device_ids(
registry.async_update_entity(entity.entity_id, new_unique_id=new_unique_id) registry.async_update_entity(entity.entity_id, new_unique_id=new_unique_id)
except ValueError as err: except ValueError as err:
_LOGGER.warning( _LOGGER.warning(
"Could not migrate entity %s (old unique_id: %s, new unique_id: %s): %s", (
"Could not migrate entity %s (old unique_id: %s, new unique_id:"
" %s): %s"
),
entity.entity_id, entity.entity_id,
entity.unique_id, entity.unique_id,
new_unique_id, new_unique_id,

View file

@ -4,4 +4,4 @@ from datetime import timedelta
DOMAIN = "upcloud" DOMAIN = "upcloud"
DEFAULT_SCAN_INTERVAL = timedelta(seconds=60) DEFAULT_SCAN_INTERVAL = timedelta(seconds=60)
CONFIG_ENTRY_UPDATE_SIGNAL_TEMPLATE = f"{DOMAIN}_config_entry_update:" "{}" CONFIG_ENTRY_UPDATE_SIGNAL_TEMPLATE = f"{DOMAIN}_config_entry_update:{{}}"

View file

@ -291,8 +291,10 @@ class VenstarThermostat(VenstarEntity, ClimateEntity):
else: else:
success = False success = False
_LOGGER.error( _LOGGER.error(
(
"The thermostat is currently not in a mode " "The thermostat is currently not in a mode "
"that supports target temperature: %s", "that supports target temperature: %s"
),
operation_mode, operation_mode,
) )

View file

@ -156,7 +156,10 @@ class VeSyncTunableWhiteLightHA(VeSyncBaseLight, LightEntity):
except ValueError: except ValueError:
# deal if any unexpected/non numeric value # deal if any unexpected/non numeric value
_LOGGER.debug( _LOGGER.debug(
"VeSync - received unexpected 'color_temp_pct' value from pyvesync api: %s", (
"VeSync - received unexpected 'color_temp_pct' value from pyvesync"
" api: %s"
),
result, result,
) )
return 0 return 0

View file

@ -68,7 +68,9 @@ def setup_platform(
digest_auth=config[CONF_AUTHENTICATION] == HTTP_DIGEST_AUTHENTICATION, digest_auth=config[CONF_AUTHENTICATION] == HTTP_DIGEST_AUTHENTICATION,
sec_lvl=config[CONF_SECURITY_LEVEL], sec_lvl=config[CONF_SECURITY_LEVEL],
), ),
"stream_source": f"rtsp://{creds}@{config[CONF_IP_ADDRESS]}:554/{config[CONF_STREAM_PATH]}", "stream_source": (
f"rtsp://{creds}@{config[CONF_IP_ADDRESS]}:554/{config[CONF_STREAM_PATH]}"
),
} }
add_entities([VivotekCam(**args)], True) add_entities([VivotekCam(**args)], True)

View file

@ -30,7 +30,8 @@ def validate_apps(config: ConfigType) -> ConfigType:
and config[CONF_DEVICE_CLASS] != MediaPlayerDeviceClass.TV and config[CONF_DEVICE_CLASS] != MediaPlayerDeviceClass.TV
): ):
raise vol.Invalid( raise vol.Invalid(
f"'{CONF_APPS}' can only be used if {CONF_DEVICE_CLASS}' is '{MediaPlayerDeviceClass.TV}'" f"'{CONF_APPS}' can only be used if {CONF_DEVICE_CLASS}' is"
f" '{MediaPlayerDeviceClass.TV}'"
) )
return config return config

View file

@ -261,9 +261,11 @@ class VizioConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
# their configuration.yaml or to proceed with config flow pairing. We # their configuration.yaml or to proceed with config flow pairing. We
# will also provide contextual message to user explaining why # will also provide contextual message to user explaining why
_LOGGER.warning( _LOGGER.warning(
(
"Couldn't complete configuration.yaml import: '%s' key is " "Couldn't complete configuration.yaml import: '%s' key is "
"missing. Either provide '%s' key in configuration.yaml or " "missing. Either provide '%s' key in configuration.yaml or "
"finish setup by completing configuration via frontend", "finish setup by completing configuration via frontend"
),
CONF_ACCESS_TOKEN, CONF_ACCESS_TOKEN,
CONF_ACCESS_TOKEN, CONF_ACCESS_TOKEN,
) )

View file

@ -92,7 +92,9 @@ class VolvoOnCallConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
): vol.In( ): vol.In(
{ {
UNIT_SYSTEM_METRIC: "Metric", UNIT_SYSTEM_METRIC: "Metric",
UNIT_SYSTEM_SCANDINAVIAN_MILES: "Metric with Scandinavian Miles", UNIT_SYSTEM_SCANDINAVIAN_MILES: (
"Metric with Scandinavian Miles"
),
UNIT_SYSTEM_IMPERIAL: "Imperial", UNIT_SYSTEM_IMPERIAL: "Imperial",
} }
), ),

View file

@ -68,9 +68,14 @@ class VulcanCalendarEntity(CalendarEntity):
"identifiers": {(DOMAIN, f"calendar_{self.student_info['id']}")}, "identifiers": {(DOMAIN, f"calendar_{self.student_info['id']}")},
"entry_type": DeviceEntryType.SERVICE, "entry_type": DeviceEntryType.SERVICE,
"name": f"{self.student_info['full_name']}: Calendar", "name": f"{self.student_info['full_name']}: Calendar",
"model": f"{self.student_info['full_name']} - {self.student_info['class']} {self.student_info['school']}", "model": (
f"{self.student_info['full_name']} -"
f" {self.student_info['class']} {self.student_info['school']}"
),
"manufacturer": "Uonet +", "manufacturer": "Uonet +",
"configuration_url": f"https://uonetplus.vulcan.net.pl/{self.student_info['symbol']}", "configuration_url": (
f"https://uonetplus.vulcan.net.pl/{self.student_info['symbol']}"
),
} }
@property @property

View file

@ -218,7 +218,9 @@ class VulcanFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
await self.async_set_unique_id(str(new_students[0].pupil.id)) await self.async_set_unique_id(str(new_students[0].pupil.id))
self._abort_if_unique_id_configured() self._abort_if_unique_id_configured()
return self.async_create_entry( return self.async_create_entry(
title=f"{new_students[0].pupil.first_name} {new_students[0].pupil.last_name}", title=(
f"{new_students[0].pupil.first_name} {new_students[0].pupil.last_name}"
),
data={ data={
"student_id": str(new_students[0].pupil.id), "student_id": str(new_students[0].pupil.id),
"keystore": keystore.as_dict, "keystore": keystore.as_dict,
@ -282,7 +284,9 @@ class VulcanFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
if str(student.pupil.id) == str(entry.data["student_id"]): if str(student.pupil.id) == str(entry.data["student_id"]):
self.hass.config_entries.async_update_entry( self.hass.config_entries.async_update_entry(
entry, entry,
title=f"{student.pupil.first_name} {student.pupil.last_name}", title=(
f"{student.pupil.first_name} {student.pupil.last_name}"
),
data={ data={
"student_id": str(student.pupil.id), "student_id": str(student.pupil.id),
"keystore": keystore.as_dict, "keystore": keystore.as_dict,

View file

@ -59,7 +59,7 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
_LOGGER.error("Failed to make update API request because: %s", ex) _LOGGER.error("Failed to make update API request because: %s", ex)
persistent_notification.create( persistent_notification.create(
hass, hass,
"Error: {}" "".format(ex), f"Error: {ex}",
title=NOTIFICATION_TITLE, title=NOTIFICATION_TITLE,
notification_id=NOTIFICATION_ID, notification_id=NOTIFICATION_ID,
) )

View file

@ -96,8 +96,10 @@ class WaterFurnaceData(threading.Thread):
_LOGGER.error("Failed to refresh login credentials. Thread stopped") _LOGGER.error("Failed to refresh login credentials. Thread stopped")
persistent_notification.create( persistent_notification.create(
self.hass, self.hass,
(
"Error:<br/>Connection to waterfurnace website failed " "Error:<br/>Connection to waterfurnace website failed "
"the maximum number of times. Thread has stopped", "the maximum number of times. Thread has stopped"
),
title=NOTIFICATION_TITLE, title=NOTIFICATION_TITLE,
notification_id=NOTIFICATION_ID, notification_id=NOTIFICATION_ID,
) )

View file

@ -297,9 +297,11 @@ class WeatherEntity(Entity):
"https://github.com/home-assistant/core/issues?q=is%3Aopen+is%3Aissue" "https://github.com/home-assistant/core/issues?q=is%3Aopen+is%3Aissue"
) )
_LOGGER.warning( _LOGGER.warning(
(
"%s::%s is overriding deprecated methods on an instance of " "%s::%s is overriding deprecated methods on an instance of "
"WeatherEntity, this is not valid and will be unsupported " "WeatherEntity, this is not valid and will be unsupported "
"from Home Assistant 2023.1. Please %s", "from Home Assistant 2023.1. Please %s"
),
cls.__module__, cls.__module__,
cls.__name__, cls.__name__,
report_issue, report_issue,

View file

@ -100,7 +100,8 @@ def cmd(
except WEBOSTV_EXCEPTIONS as exc: except WEBOSTV_EXCEPTIONS as exc:
if self.state != MediaPlayerState.OFF: if self.state != MediaPlayerState.OFF:
raise HomeAssistantError( raise HomeAssistantError(
f"Error calling {func.__name__} on entity {self.entity_id}, state:{self.state}" f"Error calling {func.__name__} on entity {self.entity_id},"
f" state:{self.state}"
) from exc ) from exc
_LOGGER.warning( _LOGGER.warning(
"Error calling %s on entity %s, state:%s, error: %r", "Error calling %s on entity %s, state:%s, error: %r",

View file

@ -155,8 +155,11 @@ class WebSocketHandler:
return return
self._logger.error( self._logger.error(
"Client unable to keep up with pending messages. Stayed over %s for %s seconds. " (
"The system's load is too high or an integration is misbehaving", "Client unable to keep up with pending messages. Stayed over %s for %s"
" seconds. The system's load is too high or an integration is"
" misbehaving"
),
PENDING_MSG_PEAK, PENDING_MSG_PEAK,
PENDING_MSG_PEAK_TIME, PENDING_MSG_PEAK_TIME,
) )

View file

@ -118,8 +118,7 @@ class WirelessTagPlatform:
) )
except Exception as ex: # pylint: disable=broad-except except Exception as ex: # pylint: disable=broad-except
_LOGGER.error( _LOGGER.error(
"Unable to handle tag update:\ "Unable to handle tag update: %s error: %s",
%s error: %s",
str(tag), str(tag),
str(ex), str(ex),
) )
@ -213,8 +212,14 @@ class WirelessTagBaseSensor(Entity):
"""Return the state attributes.""" """Return the state attributes."""
return { return {
ATTR_BATTERY_LEVEL: int(self._tag.battery_remaining * 100), ATTR_BATTERY_LEVEL: int(self._tag.battery_remaining * 100),
ATTR_VOLTAGE: f"{self._tag.battery_volts:.2f}{UnitOfElectricPotential.VOLT}", ATTR_VOLTAGE: (
ATTR_TAG_SIGNAL_STRENGTH: f"{self._tag.signal_strength}{SIGNAL_STRENGTH_DECIBELS_MILLIWATT}", f"{self._tag.battery_volts:.2f}{UnitOfElectricPotential.VOLT}"
),
ATTR_TAG_SIGNAL_STRENGTH: (
f"{self._tag.signal_strength}{SIGNAL_STRENGTH_DECIBELS_MILLIWATT}"
),
ATTR_TAG_OUT_OF_RANGE: not self._tag.is_in_range, ATTR_TAG_OUT_OF_RANGE: not self._tag.is_in_range,
ATTR_TAG_POWER_CONSUMPTION: f"{self._tag.power_consumption:.2f}{PERCENTAGE}", ATTR_TAG_POWER_CONSUMPTION: (
f"{self._tag.power_consumption:.2f}{PERCENTAGE}"
),
} }

View file

@ -205,7 +205,10 @@ async def async_webhook_handler(
data_manager = get_data_manager_by_webhook_id(hass, webhook_id) data_manager = get_data_manager_by_webhook_id(hass, webhook_id)
if not data_manager: if not data_manager:
_LOGGER.error( _LOGGER.error(
"Webhook id %s not handled by data manager. This is a bug and should be reported", (
"Webhook id %s not handled by data manager. This is a bug and should be"
" reported"
),
webhook_id, webhook_id,
) )
return json_message_response("User not found", message_code=1) return json_message_response("User not found", message_code=1)

View file

@ -27,8 +27,10 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
if coordinator.data.info.leds.cct: if coordinator.data.info.leds.cct:
LOGGER.error( LOGGER.error(
(
"WLED device '%s' has a CCT channel, which is not supported by " "WLED device '%s' has a CCT channel, which is not supported by "
"this integration", "this integration"
),
entry.title, entry.title,
) )
return False return False

View file

@ -57,8 +57,10 @@ def setup_platform(
response = api.api_get("profile") response = api.api_get("profile")
if not response.ok: if not response.ok:
_LOGGER.error( _LOGGER.error(
(
"Can't setup X API connection. Check your account or " "Can't setup X API connection. Check your account or "
"api key on xapi.us. Code: %s Description: %s ", "api key on xapi.us. Code: %s Description: %s "
),
response.status_code, response.status_code,
response.reason, response.reason,
) )

View file

@ -105,8 +105,10 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
gateway.write_to_hub(gateway.sid, join_permission="yes") gateway.write_to_hub(gateway.sid, join_permission="yes")
persistent_notification.async_create( persistent_notification.async_create(
hass, hass,
(
"Join permission enabled for 30 seconds! " "Join permission enabled for 30 seconds! "
"Please press the pairing button of the new device once.", "Please press the pairing button of the new device once."
),
title="Xiaomi Aqara Gateway", title="Xiaomi Aqara Gateway",
) )

View file

@ -162,7 +162,10 @@ class XiaomiAqaraFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
name.startswith(ZEROCONF_GATEWAY) or name.startswith(ZEROCONF_ACPARTNER) name.startswith(ZEROCONF_GATEWAY) or name.startswith(ZEROCONF_ACPARTNER)
): ):
_LOGGER.debug( _LOGGER.debug(
"Xiaomi device '%s' discovered with host %s, not identified as xiaomi aqara gateway", (
"Xiaomi device '%s' discovered with host %s, not identified as"
" xiaomi aqara gateway"
),
name, name,
self.host, self.host,
) )

View file

@ -70,8 +70,7 @@ class XiaomiGatewayLight(XiaomiDevice, LightEntity):
rgbhexstr = f"{value:x}" rgbhexstr = f"{value:x}"
if len(rgbhexstr) > 8: if len(rgbhexstr) > 8:
_LOGGER.error( _LOGGER.error(
"Light RGB data error." "Light RGB data error. Can't be more than 8 characters. Received: %s",
" Can't be more than 8 characters. Received: %s",
rgbhexstr, rgbhexstr,
) )
return False return False

View file

@ -153,9 +153,11 @@ def get_platforms(config_entry):
if model.startswith(air_monitor_model): if model.startswith(air_monitor_model):
return AIR_MONITOR_PLATFORMS return AIR_MONITOR_PLATFORMS
_LOGGER.error( _LOGGER.error(
(
"Unsupported device found! Please create an issue at " "Unsupported device found! Please create an issue at "
"https://github.com/syssi/xiaomi_airpurifier/issues " "https://github.com/syssi/xiaomi_airpurifier/issues "
"and provide the following data: %s", "and provide the following data: %s"
),
model, model,
) )
return [] return []
@ -336,9 +338,11 @@ async def async_create_miio_device_and_coordinator(
device = Fan(host, token, model=model) device = Fan(host, token, model=model)
else: else:
_LOGGER.error( _LOGGER.error(
(
"Unsupported device found! Please create an issue at " "Unsupported device found! Please create an issue at "
"https://github.com/syssi/xiaomi_airpurifier/issues " "https://github.com/syssi/xiaomi_airpurifier/issues "
"and provide the following data: %s", "and provide the following data: %s"
),
model, model,
) )
return return

View file

@ -92,8 +92,10 @@ class ConnectXiaomiGateway:
self._gateway_device.discover_devices() self._gateway_device.discover_devices()
except DeviceException as error: except DeviceException as error:
_LOGGER.info( _LOGGER.info(
(
"DeviceException during getting subdevices of xiaomi gateway" "DeviceException during getting subdevices of xiaomi gateway"
" with host %s, trying cloud to obtain subdevices: %s", " with host %s, trying cloud to obtain subdevices: %s"
),
self._host, self._host,
error, error,
) )
@ -114,8 +116,10 @@ class ConnectXiaomiGateway:
miio_cloud = MiCloud(self._cloud_username, self._cloud_password) miio_cloud = MiCloud(self._cloud_username, self._cloud_password)
if not miio_cloud.login(): if not miio_cloud.login():
raise SetupException( raise SetupException(
"Failed to login to Xiaomi Miio Cloud during setup of Xiaomi" (
f" gateway with host {self._host}", "Failed to login to Xiaomi Miio Cloud during setup of"
f" Xiaomi gateway with host {self._host}"
),
) )
devices_raw = miio_cloud.get_devices(self._cloud_country) devices_raw = miio_cloud.get_devices(self._cloud_country)
self._gateway_device.get_devices_from_dict(devices_raw) self._gateway_device.get_devices_from_dict(devices_raw)
@ -125,7 +129,8 @@ class ConnectXiaomiGateway:
) from error ) from error
except DeviceException as error: except DeviceException as error:
raise SetupException( raise SetupException(
f"DeviceException during setup of xiaomi gateway with host {self._host}" "DeviceException during setup of xiaomi gateway with host"
f" {self._host}"
) from error ) from error

View file

@ -198,9 +198,11 @@ async def async_setup_entry(
hass.data[DATA_KEY][host] = entity hass.data[DATA_KEY][host] = entity
else: else:
_LOGGER.error( _LOGGER.error(
(
"Unsupported device found! Please create an issue at " "Unsupported device found! Please create an issue at "
"https://github.com/syssi/philipslight/issues " "https://github.com/syssi/philipslight/issues "
"and provide the following data: %s", "and provide the following data: %s"
),
model, model,
) )
return return
@ -445,8 +447,10 @@ class XiaomiPhilipsBulb(XiaomiPhilipsGenericLight):
if ATTR_BRIGHTNESS in kwargs and ATTR_COLOR_TEMP in kwargs: if ATTR_BRIGHTNESS in kwargs and ATTR_COLOR_TEMP in kwargs:
_LOGGER.debug( _LOGGER.debug(
(
"Setting brightness and color temperature: " "Setting brightness and color temperature: "
"%s %s%%, %s mireds, %s%% cct", "%s %s%%, %s mireds, %s%% cct"
),
brightness, brightness,
percent_brightness, percent_brightness,
color_temp, color_temp,
@ -843,8 +847,10 @@ class XiaomiPhilipsMoonlightLamp(XiaomiPhilipsBulb):
elif ATTR_BRIGHTNESS in kwargs and ATTR_COLOR_TEMP in kwargs: elif ATTR_BRIGHTNESS in kwargs and ATTR_COLOR_TEMP in kwargs:
_LOGGER.debug( _LOGGER.debug(
(
"Setting brightness and color temperature: " "Setting brightness and color temperature: "
"%s %s%%, %s mireds, %s%% cct", "%s %s%%, %s mireds, %s%% cct"
),
brightness, brightness,
percent_brightness, percent_brightness,
color_temp, color_temp,

View file

@ -470,9 +470,11 @@ async def async_setup_other_entry(hass, config_entry, async_add_entities):
hass.data[DATA_KEY][host] = device hass.data[DATA_KEY][host] = device
else: else:
_LOGGER.error( _LOGGER.error(
(
"Unsupported device found! Please create an issue at " "Unsupported device found! Please create an issue at "
"https://github.com/rytilahti/python-miio/issues " "https://github.com/rytilahti/python-miio/issues "
"and provide the following data: %s", "and provide the following data: %s"
),
model, model,
) )

View file

@ -81,7 +81,8 @@ class YaleAlarmDevice(YaleAlarmEntity, AlarmControlPanelEntity):
) )
except YALE_ALL_ERRORS as error: except YALE_ALL_ERRORS as error:
raise HomeAssistantError( raise HomeAssistantError(
f"Could not set alarm for {self.coordinator.entry.data[CONF_NAME]}: {error}" f"Could not set alarm for {self.coordinator.entry.data[CONF_NAME]}:"
f" {error}"
) from error ) from error
if alarm_state: if alarm_state:

View file

@ -233,7 +233,9 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
{ {
vol.Required(CONF_ADDRESS): vol.In( vol.Required(CONF_ADDRESS): vol.In(
{ {
service_info.address: f"{service_info.name} ({service_info.address})" service_info.address: (
f"{service_info.name} ({service_info.address})"
)
for service_info in self._discovered_devices.values() for service_info in self._discovered_devices.values()
} }
), ),

View file

@ -463,7 +463,8 @@ class MusicCastMediaPlayer(MusicCastDeviceEntity, MediaPlayerEntity):
await self.coordinator.musiccast.tuner_previous_station() await self.coordinator.musiccast.tuner_previous_station()
else: else:
raise HomeAssistantError( raise HomeAssistantError(
"Service previous track is not supported for non NetUSB or Tuner sources." "Service previous track is not supported for non NetUSB or Tuner"
" sources."
) )
async def async_media_next_track(self) -> None: async def async_media_next_track(self) -> None:
@ -720,7 +721,10 @@ class MusicCastMediaPlayer(MusicCastDeviceEntity, MediaPlayerEntity):
network_join = await client.async_client_join(group, self) network_join = await client.async_client_join(group, self)
except MusicCastGroupException: except MusicCastGroupException:
_LOGGER.warning( _LOGGER.warning(
"%s is struggling to update its group data. Will retry perform the update", (
"%s is struggling to update its group data. Will retry"
" perform the update"
),
client.entity_id, client.entity_id,
) )
network_join = await client.async_client_join(group, self) network_join = await client.async_client_join(group, self)
@ -786,8 +790,10 @@ class MusicCastMediaPlayer(MusicCastDeviceEntity, MediaPlayerEntity):
if self.musiccast_zone_entity.is_server: if self.musiccast_zone_entity.is_server:
# If one of the zones of the device is a server, we need to unjoin first. # If one of the zones of the device is a server, we need to unjoin first.
_LOGGER.debug( _LOGGER.debug(
(
"%s is a server of a group and has to stop distribution " "%s is a server of a group and has to stop distribution "
"to use MusicCast for %s", "to use MusicCast for %s"
),
self.musiccast_zone_entity.entity_id, self.musiccast_zone_entity.entity_id,
self.entity_id, self.entity_id,
) )

View file

@ -96,7 +96,10 @@ class DiscoverYandexTransport(SensorEntity):
data = yandex_reply["data"] data = yandex_reply["data"]
except KeyError as key_error: except KeyError as key_error:
_LOGGER.warning( _LOGGER.warning(
"Exception KeyError was captured, missing key is %s. Yandex returned: %s", (
"Exception KeyError was captured, missing key is %s. Yandex"
" returned: %s"
),
key_error, key_error,
yandex_reply, yandex_reply,
) )

View file

@ -96,7 +96,10 @@ class ZamgConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
try: try:
if station_id not in await self._client.zamg_stations(): if station_id not in await self._client.zamg_stations():
LOGGER.warning( LOGGER.warning(
"Configured station_id %s could not be found at zamg, trying to add nearest weather station instead", (
"Configured station_id %s could not be found at zamg, trying to"
" add nearest weather station instead"
),
station_id, station_id,
) )
latitude = config.get(CONF_LATITUDE) or self.hass.config.latitude latitude = config.get(CONF_LATITUDE) or self.hass.config.latitude

View file

@ -579,7 +579,10 @@ def _suppress_invalid_properties(properties: dict) -> None:
if len(prop_value.encode("utf-8")) > MAX_PROPERTY_VALUE_LEN: if len(prop_value.encode("utf-8")) > MAX_PROPERTY_VALUE_LEN:
_LOGGER.error( _LOGGER.error(
"The property '%s' was suppressed because it is longer than the maximum length of %d bytes: %s", (
"The property '%s' was suppressed because it is longer than the"
" maximum length of %d bytes: %s"
),
prop, prop,
MAX_PROPERTY_VALUE_LEN, MAX_PROPERTY_VALUE_LEN,
prop_value, prop_value,
@ -593,7 +596,10 @@ def _truncate_location_name_to_valid(location_name: str) -> str:
return location_name return location_name
_LOGGER.warning( _LOGGER.warning(
"The location name was truncated because it is longer than the maximum length of %d bytes: %s", (
"The location name was truncated because it is longer than the maximum"
" length of %d bytes: %s"
),
MAX_NAME_LEN, MAX_NAME_LEN,
location_name, location_name,
) )

View file

@ -14,7 +14,11 @@ def install_multiple_zeroconf_catcher(hass_zc: HaZeroconf) -> None:
def new_zeroconf_new(self: zeroconf.Zeroconf, *k: Any, **kw: Any) -> HaZeroconf: def new_zeroconf_new(self: zeroconf.Zeroconf, *k: Any, **kw: Any) -> HaZeroconf:
report( report(
"attempted to create another Zeroconf instance. Please use the shared Zeroconf via await homeassistant.components.zeroconf.async_get_instance(hass)", (
"attempted to create another Zeroconf instance. Please use the shared"
" Zeroconf via await"
" homeassistant.components.zeroconf.async_get_instance(hass)"
),
exclude_integrations={"zeroconf"}, exclude_integrations={"zeroconf"},
error_if_core=False, error_if_core=False,
) )

View file

@ -821,7 +821,10 @@ async def websocket_read_zigbee_cluster_attributes(
[attribute], allow_cache=False, only_cache=False, manufacturer=manufacturer [attribute], allow_cache=False, only_cache=False, manufacturer=manufacturer
) )
_LOGGER.debug( _LOGGER.debug(
"Read attribute for: %s: [%s] %s: [%s] %s: [%s] %s: [%s] %s: [%s] %s: [%s] %s: [%s],", (
"Read attribute for: %s: [%s] %s: [%s] %s: [%s] %s: [%s] %s: [%s] %s: [%s]"
" %s: [%s],"
),
ATTR_CLUSTER_ID, ATTR_CLUSTER_ID,
cluster_id, cluster_id,
ATTR_CLUSTER_TYPE, ATTR_CLUSTER_TYPE,
@ -1286,7 +1289,10 @@ def async_load_api(hass: HomeAssistant) -> None:
manufacturer=manufacturer, manufacturer=manufacturer,
) )
_LOGGER.debug( _LOGGER.debug(
"Set attribute for: %s: [%s] %s: [%s] %s: [%s] %s: [%s] %s: [%s] %s: [%s] %s: [%s]", (
"Set attribute for: %s: [%s] %s: [%s] %s: [%s] %s: [%s] %s: [%s] %s:"
" [%s] %s: [%s]"
),
ATTR_CLUSTER_ID, ATTR_CLUSTER_ID,
cluster_id, cluster_id,
ATTR_CLUSTER_TYPE, ATTR_CLUSTER_TYPE,
@ -1338,7 +1344,10 @@ def async_load_api(hass: HomeAssistant) -> None:
manufacturer=manufacturer, manufacturer=manufacturer,
) )
_LOGGER.debug( _LOGGER.debug(
"Issued command for: %s: [%s] %s: [%s] %s: [%s] %s: [%s] %s: [%s] %s: [%s] %s: [%s] %s: [%s]", (
"Issued command for: %s: [%s] %s: [%s] %s: [%s] %s: [%s] %s: [%s]"
" %s: [%s] %s: [%s] %s: [%s]"
),
ATTR_CLUSTER_ID, ATTR_CLUSTER_ID,
cluster_id, cluster_id,
ATTR_CLUSTER_TYPE, ATTR_CLUSTER_TYPE,