String formatting and max line length - Part 7 (#84532)

Co-authored-by: Martin Hjelmare <marhje52@gmail.com>
This commit is contained in:
Franck Nijhof 2022-12-27 11:18:56 +01:00 committed by GitHub
parent 3149c52be1
commit d4f69a3652
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
40 changed files with 249 additions and 110 deletions

View file

@ -101,7 +101,10 @@ class ColorChannel(ZigbeeChannel):
min_mireds = self.cluster.get("color_temp_physical_min", self.MIN_MIREDS)
if min_mireds == 0:
self.warning(
"[Min mireds is 0, setting to %s] Please open an issue on the quirks repo to have this device corrected",
(
"[Min mireds is 0, setting to %s] Please open an issue on the"
" quirks repo to have this device corrected"
),
self.MIN_MIREDS,
)
min_mireds = self.MIN_MIREDS
@ -113,7 +116,10 @@ class ColorChannel(ZigbeeChannel):
max_mireds = self.cluster.get("color_temp_physical_max", self.MAX_MIREDS)
if max_mireds == 0:
self.warning(
"[Max mireds is 0, setting to %s] Please open an issue on the quirks repo to have this device corrected",
(
"[Max mireds is 0, setting to %s] Please open an issue on the"
" quirks repo to have this device corrected"
),
self.MAX_MIREDS,
)
max_mireds = self.MAX_MIREDS

View file

@ -397,7 +397,10 @@ class ZHADevice(LogMixin):
or not self._channels.pools
):
self.debug(
"last_seen is %s seconds ago and ping attempts have been exhausted, marking the device unavailable",
(
"last_seen is %s seconds ago and ping attempts have been exhausted,"
" marking the device unavailable"
),
difference,
)
self.update_available(False)
@ -422,7 +425,10 @@ class ZHADevice(LogMixin):
def update_available(self, available: bool) -> None:
"""Update device availability and signal entities."""
self.debug(
"Update device availability - device available: %s - new availability: %s - changed: %s",
(
"Update device availability - device available: %s - new availability:"
" %s - changed: %s"
),
self.available,
available,
self.available ^ available,
@ -432,7 +438,8 @@ class ZHADevice(LogMixin):
if availability_changed and available:
# reinit channels then signal entities
self.debug(
"Device availability changed and device became available, reinitializing channels"
"Device availability changed and device became available,"
" reinitializing channels"
)
self.hass.async_create_task(self._async_became_available())
return
@ -562,8 +569,10 @@ class ZHADevice(LogMixin):
else:
names.append(
{
ATTR_NAME: f"unknown {endpoint.device_type} device_type "
f"of 0x{(endpoint.profile_id or 0xFFFF):04x} profile id"
ATTR_NAME: (
f"unknown {endpoint.device_type} device_type "
f"of 0x{(endpoint.profile_id or 0xFFFF):04x} profile id"
)
}
)
device_info[ATTR_ENDPOINT_NAMES] = names
@ -696,7 +705,8 @@ class ZHADevice(LogMixin):
)
except KeyError as exc:
raise ValueError(
f"Cluster {cluster_id} not found on endpoint {endpoint_id} while issuing command {command} with args {args}"
f"Cluster {cluster_id} not found on endpoint {endpoint_id} while"
f" issuing command {command} with args {args}"
) from exc
commands: dict[int, ZCLCommandDef] = (
cluster.server_commands
@ -705,7 +715,10 @@ class ZHADevice(LogMixin):
)
if args is not None:
self.warning(
"args [%s] are deprecated and should be passed with the params key. The parameter names are: %s",
(
"args [%s] are deprecated and should be passed with the params key."
" The parameter names are: %s"
),
args,
[field.name for field in commands[command].schema.fields],
)
@ -790,7 +803,10 @@ class ZHADevice(LogMixin):
await self._zigpy_device.endpoints[endpoint_id].remove_from_group(group_id)
except (zigpy.exceptions.ZigbeeException, asyncio.TimeoutError) as ex:
self.debug(
"Failed to remove endpoint: %s for device '%s' from group: 0x%04x ex: %s",
(
"Failed to remove endpoint: %s for device '%s' from group: 0x%04x"
" ex: %s"
),
endpoint_id,
self._zigpy_device.ieee,
group_id,

View file

@ -209,7 +209,10 @@ class ZHAGateway:
zha_device.available = delta < zha_device.consider_unavailable_time
delta_msg = f"{str(timedelta(seconds=delta))} ago"
_LOGGER.debug(
"[%s](%s) restored as '%s', last seen: %s, consider_unavailable_time: %s seconds",
(
"[%s](%s) restored as '%s', last seen: %s,"
" consider_unavailable_time: %s seconds"
),
zha_device.nwk,
zha_device.name,
"available" if zha_device.available else "unavailable",
@ -649,7 +652,10 @@ class ZHAGateway:
tasks = []
for member in members:
_LOGGER.debug(
"Adding member with IEEE: %s and endpoint ID: %s to group: %s:0x%04x",
(
"Adding member with IEEE: %s and endpoint ID: %s to group:"
" %s:0x%04x"
),
member.ieee,
member.endpoint_id,
name,

View file

@ -103,7 +103,10 @@ class ZHAGroupMember(LogMixin):
].remove_from_group(self._zha_group.group_id)
except (zigpy.exceptions.ZigbeeException, asyncio.TimeoutError) as ex:
self.debug(
"Failed to remove endpoint: %s for device '%s' from group: 0x%04x ex: %s",
(
"Failed to remove endpoint: %s for device '%s' from group: 0x%04x"
" ex: %s"
),
self._endpoint_id,
self._zha_device.ieee,
self._zha_group.group_id,

View file

@ -349,10 +349,7 @@ def retryable_req(
if delay:
delay = uniform(delay * 0.75, delay * 1.25)
channel.debug(
(
"%s: retryable request #%d failed: %s. "
"Retrying in %ss"
),
"%s: retryable request #%d failed: %s. Retrying in %ss",
func.__name__,
try_count,
ex,

View file

@ -210,12 +210,14 @@ async def _execute_channel_command_based_action(
if action_channel is None:
raise InvalidDeviceAutomationConfig(
f"Unable to execute channel action - channel: {channel_name} action: {action_type}"
f"Unable to execute channel action - channel: {channel_name} action:"
f" {action_type}"
)
if not hasattr(action_channel, action_type):
raise InvalidDeviceAutomationConfig(
f"Unable to execute channel action - channel: {channel_name} action: {action_type}"
f"Unable to execute channel action - channel: {channel_name} action:"
f" {action_type}"
)
await getattr(action_channel, action_type)(**config)

View file

@ -113,7 +113,8 @@ class BaseFan(FanEntity):
"""Set the preset mode for the fan."""
if preset_mode not in self.preset_modes:
raise NotValidPresetModeError(
f"The preset_mode {preset_mode} is not a valid preset_mode: {self.preset_modes}"
f"The preset_mode {preset_mode} is not a valid preset_mode:"
f" {self.preset_modes}"
)
await self._async_set_fan_mode(NAME_TO_PRESET_MODE[preset_mode])
@ -288,7 +289,8 @@ class IkeaFan(BaseFan, ZhaEntity):
"""Set the preset mode for the fan."""
if preset_mode not in self.preset_modes:
raise NotValidPresetModeError(
f"The preset_mode {preset_mode} is not a valid preset_mode: {self.preset_modes}"
f"The preset_mode {preset_mode} is not a valid preset_mode:"
f" {self.preset_modes}"
)
await self._async_set_fan_mode(IKEA_NAME_TO_PRESET_MODE[preset_mode])

View file

@ -94,7 +94,10 @@ async def async_attach_trigger(
if not (zone_state := hass.states.get(zone_entity_id)):
_LOGGER.warning(
"Automation '%s' is referencing non-existing zone '%s' in a zone trigger",
(
"Automation '%s' is referencing non-existing zone '%s' in a zone"
" trigger"
),
trigger_info["name"],
zone_entity_id,
)

View file

@ -377,7 +377,11 @@ class ControllerEvents:
async_dispatcher_send(
self.hass,
f"{DOMAIN}_{get_valueless_base_unique_id(self.driver_events.driver, node)}_remove_entity",
(
f"{DOMAIN}_"
f"{get_valueless_base_unique_id(self.driver_events.driver, node)}_"
"remove_entity"
),
)
else:
self.remove_device(device)

View file

@ -63,8 +63,8 @@ class ZWaveNodePingButton(ButtonEntity):
async def async_poll_value(self, _: bool) -> None:
"""Poll a value."""
LOGGER.error(
"There is no value to refresh for this entity so the zwave_js.refresh_value "
"service won't work for it"
"There is no value to refresh for this entity so the zwave_js.refresh_value"
" service won't work for it"
)
async def async_added_to_hass(self) -> None:

View file

@ -181,7 +181,8 @@ class ValueMappingZwaveFan(ZwaveFan):
return
raise NotValidPresetModeError(
f"The preset_mode {preset_mode} is not a valid preset_mode: {self.preset_modes}"
f"The preset_mode {preset_mode} is not a valid preset_mode:"
f" {self.preset_modes}"
)
@property

View file

@ -490,8 +490,8 @@ class ZWaveNodeStatusSensor(SensorEntity):
async def async_poll_value(self, _: bool) -> None:
"""Poll a value."""
LOGGER.error(
"There is no value to refresh for this entity so the zwave_js.refresh_value "
"service won't work for it"
"There is no value to refresh for this entity so the zwave_js.refresh_value"
" service won't work for it"
)
@callback

View file

@ -246,8 +246,8 @@ class ZWaveNodeFirmwareUpdate(UpdateEntity):
async def async_poll_value(self, _: bool) -> None:
"""Poll a value."""
LOGGER.error(
"There is no value to refresh for this entity so the zwave_js.refresh_value "
"service won't work for it"
"There is no value to refresh for this entity so the zwave_js.refresh_value"
" service won't work for it"
)
async def async_added_to_hass(self) -> None:

View file

@ -289,7 +289,8 @@ async def async_get_registry(hass: HomeAssistant) -> AreaRegistry:
This is deprecated and will be removed in the future. Use async_get instead.
"""
report(
"uses deprecated `async_get_registry` to access area registry, use async_get instead"
"uses deprecated `async_get_registry` to access area registry, use async_get"
" instead"
)
return async_get(hass)

View file

@ -385,7 +385,10 @@ def async_numeric_state( # noqa: C901
except (ValueError, TypeError) as ex:
raise ConditionErrorMessage(
"numeric_state",
f"the 'below' entity {below} state '{below_entity.state}' cannot be processed as a number",
(
f"the 'below' entity {below} state '{below_entity.state}'"
" cannot be processed as a number"
),
) from ex
elif fvalue >= below:
condition_trace_set_result(False, state=fvalue, wanted_state_below=below)
@ -413,7 +416,10 @@ def async_numeric_state( # noqa: C901
except (ValueError, TypeError) as ex:
raise ConditionErrorMessage(
"numeric_state",
f"the 'above' entity {above} state '{above_entity.state}' cannot be processed as a number",
(
f"the 'above' entity {above} state '{above_entity.state}'"
" cannot be processed as a number"
),
) from ex
elif fvalue <= above:
condition_trace_set_result(False, state=fvalue, wanted_state_above=above)
@ -889,7 +895,10 @@ def zone_from_config(config: ConfigType) -> ConditionCheckerType:
errors.append(
ConditionErrorMessage(
"zone",
f"error matching {entity_id} with {zone_entity_id}: {ex.message}",
(
f"error matching {entity_id} with {zone_entity_id}:"
f" {ex.message}"
),
)
)

View file

@ -217,7 +217,8 @@ class AbstractOAuth2FlowHandler(config_entries.ConfigFlow, metaclass=ABCMeta):
"""Instantiate config flow."""
if self.DOMAIN == "":
raise TypeError(
f"Can't instantiate class {self.__class__.__name__} without DOMAIN being set"
f"Can't instantiate class {self.__class__.__name__} without DOMAIN"
" being set"
)
self.external_data: Any = None
@ -290,7 +291,9 @@ class AbstractOAuth2FlowHandler(config_entries.ConfigFlow, metaclass=ABCMeta):
return self.async_abort(
reason="no_url_available",
description_placeholders={
"docs_url": "https://www.home-assistant.io/more-info/no-url-available"
"docs_url": (
"https://www.home-assistant.io/more-info/no-url-available"
)
},
)

View file

@ -40,8 +40,10 @@ def deprecated_substitute(
if not warnings.get(module_name):
logger = logging.getLogger(module_name)
logger.warning(
"'%s' is deprecated. Please rename '%s' to "
"'%s' in '%s' to ensure future support.",
(
"'%s' is deprecated. Please rename '%s' to "
"'%s' in '%s' to ensure future support."
),
substitute_name,
substitute_name,
func.__name__,
@ -79,8 +81,10 @@ def get_deprecated(
logger = logging.getLogger(module_name)
logger.warning(
"'%s' is deprecated. Please rename '%s' to '%s' in your "
"configuration file.",
(
"'%s' is deprecated. Please rename '%s' to '%s' in your "
"configuration file."
),
old_name,
old_name,
new_name,
@ -133,7 +137,10 @@ def _print_deprecation_warning(obj: Any, replacement: str, description: str) ->
_, integration, path = get_integration_frame()
if path == "custom_components/":
logger.warning(
"%s was called from %s, this is a deprecated %s. Use %s instead, please report this to the maintainer of %s",
(
"%s was called from %s, this is a deprecated %s. Use %s instead,"
" please report this to the maintainer of %s"
),
obj.__name__,
integration,
description,

View file

@ -345,9 +345,11 @@ class DeviceRegistry:
if isinstance(entry_type, str) and not isinstance(entry_type, DeviceEntryType):
report( # type: ignore[unreachable]
"uses str for device registry entry_type. This is deprecated and will "
"stop working in Home Assistant 2022.3, it should be updated to use "
"DeviceEntryType instead",
(
"uses str for device registry entry_type. This is deprecated and"
" will stop working in Home Assistant 2022.3, it should be updated"
" to use DeviceEntryType instead"
),
error_if_core=False,
)
entry_type = DeviceEntryType(entry_type)
@ -417,9 +419,11 @@ class DeviceRegistry:
disabled_by, DeviceEntryDisabler
):
report( # type: ignore[unreachable]
"uses str for device registry disabled_by. This is deprecated and will "
"stop working in Home Assistant 2022.3, it should be updated to use "
"DeviceEntryDisabler instead",
(
"uses str for device registry disabled_by. This is deprecated and"
" will stop working in Home Assistant 2022.3, it should be updated"
" to use DeviceEntryDisabler instead"
),
error_if_core=False,
)
disabled_by = DeviceEntryDisabler(disabled_by)
@ -698,7 +702,8 @@ async def async_get_registry(hass: HomeAssistant) -> DeviceRegistry:
This is deprecated and will be removed in the future. Use async_get instead.
"""
report(
"uses deprecated `async_get_registry` to access device registry, use async_get instead"
"uses deprecated `async_get_registry` to access device registry, use async_get"
" instead"
)
return async_get(hass)

View file

@ -579,7 +579,10 @@ class Entity(ABC):
self._disabled_reported = True
assert self.platform is not None
_LOGGER.warning(
"Entity %s is incorrectly being triggered for updates while it is disabled. This is a bug in the %s integration",
(
"Entity %s is incorrectly being triggered for updates while it"
" is disabled. This is a bug in the %s integration"
),
self.entity_id,
self.platform.platform_name,
)
@ -767,7 +770,8 @@ class Entity(ABC):
"""Start adding an entity to a platform."""
if self._platform_state == EntityPlatformState.ADDED:
raise HomeAssistantError(
f"Entity {self.entity_id} cannot be added a second time to an entity platform"
f"Entity {self.entity_id} cannot be added a second time to an entity"
" platform"
)
self.hass = hass

View file

@ -145,7 +145,12 @@ class EntityPlatform:
def __repr__(self) -> str:
"""Represent an EntityPlatform."""
return f"<EntityPlatform domain={self.domain} platform_name={self.platform_name} config_entry={self.config_entry}>"
return (
"<EntityPlatform "
f"domain={self.domain} "
f"platform_name={self.platform_name} "
f"config_entry={self.config_entry}>"
)
@callback
def _get_parallel_updates_semaphore(
@ -191,7 +196,10 @@ class EntityPlatform:
platform, "setup_platform"
):
self.logger.error(
"The %s platform for the %s integration does not support platform setup. Please remove it from your config.",
(
"The %s platform for the %s integration does not support platform"
" setup. Please remove it from your config."
),
self.platform_name,
self.domain,
)
@ -327,8 +335,10 @@ class EntityPlatform:
return False
except asyncio.TimeoutError:
logger.error(
"Setup of platform %s is taking longer than %s seconds."
" Startup will proceed without waiting any longer.",
(
"Setup of platform %s is taking longer than %s seconds."
" Startup will proceed without waiting any longer."
),
self.platform_name,
SLOW_SETUP_MAX_WAIT,
)
@ -514,9 +524,15 @@ class EntityPlatform:
f"Platform {self.platform_name} does not generate unique IDs. "
)
if entity.entity_id:
msg += f"ID {entity.unique_id} is already used by {registered_entity_id} - ignoring {entity.entity_id}"
msg += (
f"ID {entity.unique_id} is already used by"
f" {registered_entity_id} - ignoring {entity.entity_id}"
)
else:
msg += f"ID {entity.unique_id} already exists - ignoring {registered_entity_id}"
msg += (
f"ID {entity.unique_id} already exists - ignoring"
f" {registered_entity_id}"
)
self.logger.error(msg)
entity.add_to_platform_abort()
return

View file

@ -943,7 +943,8 @@ async def async_get_registry(hass: HomeAssistant) -> EntityRegistry:
This is deprecated and will be removed in the future. Use async_get instead.
"""
report(
"uses deprecated `async_get_registry` to access entity registry, use async_get instead"
"uses deprecated `async_get_registry` to access entity registry, use async_get"
" instead"
)
return async_get(hass)

View file

@ -884,7 +884,10 @@ class TrackTemplateResultInfo:
)
self._update_time_listeners()
_LOGGER.debug(
"Template group %s listens for %s, first render blocker by super template: %s",
(
"Template group %s listens for %s, first render blocker by super"
" template: %s"
),
self._track_templates,
self.listeners,
block_render,
@ -1106,7 +1109,10 @@ class TrackTemplateResultInfo:
)
)
_LOGGER.debug(
"Template group %s listens for %s, re-render blocker by super template: %s",
(
"Template group %s listens for %s, re-render blocker by super"
" template: %s"
),
self._track_templates,
self.listeners,
block_updates,

View file

@ -102,8 +102,10 @@ def report_integration(
_LOGGER.log(
level,
"Detected integration that %s. "
"Please report issue%s for %s using this method at %s, line %s: %s",
(
"Detected integration that %s. "
"Please report issue%s for %s using this method at %s, line %s: %s"
),
what,
extra,
integration,

View file

@ -84,7 +84,10 @@ def find_coordinates(
recursion_history.append(name)
if entity_state.state in recursion_history:
_LOGGER.error(
"Circular reference detected while trying to find coordinates of an entity. The state of %s has already been checked",
(
"Circular reference detected while trying to find coordinates of an"
" entity. The state of %s has already been checked"
),
entity_state.state,
)
return None

View file

@ -716,7 +716,10 @@ async def _handle_entity_call(
if asyncio.iscoroutine(result):
_LOGGER.error(
"Service %s for %s incorrectly returns a coroutine object. Await result instead in service handler. Report bug to integration author",
(
"Service %s for %s incorrectly returns a coroutine object. Await result"
" instead in service handler. Report bug to integration author"
),
func,
entity.entity_id,
)

View file

@ -1409,8 +1409,8 @@ def raise_no_default(function: str, value: Any) -> NoReturn:
"""Log warning if no default is specified."""
template, action = template_cv.get() or ("", "rendering or compiling")
raise ValueError(
f"Template error: {function} got invalid input '{value}' when {action} template '{template}' "
"but no default was specified"
f"Template error: {function} got invalid input '{value}' when {action} template"
f" '{template}' but no default was specified"
)
@ -1800,7 +1800,11 @@ def struct_pack(value: Any | None, format_string: str) -> bytes | None:
return pack(format_string, value)
except StructError:
_LOGGER.warning(
"Template warning: 'pack' unable to pack object '%s' with type '%s' and format_string '%s' see https://docs.python.org/3/library/struct.html for more information",
(
"Template warning: 'pack' unable to pack object '%s' with type '%s' and"
" format_string '%s' see https://docs.python.org/3/library/struct.html"
" for more information"
),
str(value),
type(value).__name__,
format_string,
@ -1814,7 +1818,11 @@ def struct_unpack(value: bytes, format_string: str, offset: int = 0) -> Any | No
return unpack_from(format_string, value, offset)[0]
except StructError:
_LOGGER.warning(
"Template warning: 'unpack' unable to unpack object '%s' with format_string '%s' and offset %s see https://docs.python.org/3/library/struct.html for more information",
(
"Template warning: 'unpack' unable to unpack object '%s' with"
" format_string '%s' and offset %s see"
" https://docs.python.org/3/library/struct.html for more information"
),
value,
format_string,
offset,

View file

@ -106,9 +106,11 @@ class _TemplateAttribute:
"""Handle a template result event callback."""
if isinstance(result, TemplateError):
_LOGGER.error(
"TemplateError('%s') "
"while processing template '%s' "
"for attribute '%s' in entity '%s'",
(
"TemplateError('%s') "
"while processing template '%s' "
"for attribute '%s' in entity '%s'"
),
result,
self.template,
self._attribute,
@ -130,10 +132,12 @@ class _TemplateAttribute:
validated = self.validator(result)
except vol.Invalid as ex:
_LOGGER.error(
"Error validating template result '%s' "
"from template '%s' "
"for attribute '%s' in entity %s "
"validation message '%s'",
(
"Error validating template result '%s' "
"from template '%s' "
"for attribute '%s' in entity %s "
"validation message '%s'"
),
result,
self.template,
self._attribute,
@ -310,7 +314,10 @@ class TemplateEntity(Entity):
if self._self_ref_update_count > len(self._template_attrs):
for update in updates:
_LOGGER.warning(
"Template loop detected while processing event: %s, skipping template render for Template[%s]",
(
"Template loop detected while processing event: %s, skipping"
" template render for Template[%s]"
),
event,
update.template.template,
)

View file

@ -118,7 +118,10 @@ def _merge_resources(
domain_resources.update(new_value)
else:
_LOGGER.error(
"An integration providing translations for %s provided invalid data: %s",
(
"An integration providing translations for %s provided invalid"
" data: %s"
),
domain,
new_value,
)

View file

@ -33,7 +33,7 @@ def run(args):
# Disable logging
logging.getLogger("homeassistant.core").setLevel(logging.CRITICAL)
parser = argparse.ArgumentParser(description=("Run a Home Assistant benchmark."))
parser = argparse.ArgumentParser(description="Run a Home Assistant benchmark.")
parser.add_argument("name", choices=BENCHMARKS)
parser.add_argument("--script", choices=["benchmark"])

View file

@ -12,7 +12,7 @@ from homeassistant.core import HomeAssistant
def run(args):
"""Handle ensure config commandline script."""
parser = argparse.ArgumentParser(
description=("Ensure a Home Assistant config exists, creates one if necessary.")
description="Ensure a Home Assistant config exists, creates one if necessary."
)
parser.add_argument(
"-c",

View file

@ -32,10 +32,7 @@ def install_osx():
os.popen(f"launchctl load -w -F {path}")
print(
"Home Assistant has been installed. \
Open it here: http://localhost:8123"
)
print("Home Assistant has been installed. Open it here: http://localhost:8123")
def uninstall_osx():

View file

@ -155,8 +155,11 @@ def check_loop(
extra = ""
_LOGGER.warning(
"Detected blocking call to %s inside the event loop. This is causing stability issues. "
"Please report issue%s for %s doing blocking calls at %s, line %s: %s",
(
"Detected blocking call to %s inside the event loop. This is causing"
" stability issues. Please report issue%s for %s doing blocking calls at"
" %s, line %s: %s"
),
func.__name__,
extra,
integration,
@ -166,9 +169,10 @@ def check_loop(
)
if strict:
raise RuntimeError(
"Blocking calls must be done in the executor or a separate thread; "
f"{advise_msg or 'Use `await hass.async_add_executor_job()`'}; "
f"at {found_frame.filename[index:]}, line {found_frame.lineno}: {(found_frame.line or '?').strip()}"
"Blocking calls must be done in the executor or a separate thread;"
f" {advise_msg or 'Use `await hass.async_add_executor_job()`'}; at"
f" {found_frame.filename[index:]}, line {found_frame.lineno}:"
f" {(found_frame.line or '?').strip()}"
)

View file

@ -48,9 +48,11 @@ METERS_TO: dict[str, Callable[[float], float]] = {
def convert(value: float, from_unit: str, to_unit: str) -> float:
"""Convert one unit of measurement to another."""
report(
"uses distance utility. This is deprecated since 2022.10 and will "
"stop working in Home Assistant 2023.4, it should be updated to use "
"unit_conversion.DistanceConverter instead",
(
"uses distance utility. This is deprecated since 2022.10 and will "
"stop working in Home Assistant 2023.4, it should be updated to use "
"unit_conversion.DistanceConverter instead"
),
error_if_core=False,
)
return DistanceConverter.convert(value, from_unit, to_unit)

View file

@ -84,7 +84,10 @@ def save_json(
dump = _orjson_default_encoder
json_data = _orjson_default_encoder(data)
except TypeError as error:
msg = f"Failed to serialize to JSON: {filename}. Bad data at {format_unserializable_data(find_paths_unserializable_data(data, dump=dump))}"
formatted_data = format_unserializable_data(
find_paths_unserializable_data(data, dump=dump)
)
msg = f"Failed to serialize to JSON: {filename}. Bad data at {formatted_data}"
_LOGGER.error(msg)
raise SerializationError(msg) from error

View file

@ -27,9 +27,11 @@ VALID_UNITS = PressureConverter.VALID_UNITS
def convert(value: float, from_unit: str, to_unit: str) -> float:
"""Convert one unit of measurement to another."""
report(
"uses pressure utility. This is deprecated since 2022.10 and will "
"stop working in Home Assistant 2023.4, it should be updated to use "
"unit_conversion.PressureConverter instead",
(
"uses pressure utility. This is deprecated since 2022.10 and will "
"stop working in Home Assistant 2023.4, it should be updated to use "
"unit_conversion.PressureConverter instead"
),
error_if_core=False,
)
return PressureConverter.convert(value, from_unit, to_unit)

View file

@ -34,9 +34,11 @@ VALID_UNITS = SpeedConverter.VALID_UNITS
def convert(value: float, from_unit: str, to_unit: str) -> float:
"""Convert one unit of measurement to another."""
report(
"uses speed utility. This is deprecated since 2022.10 and will "
"stop working in Home Assistant 2023.4, it should be updated to use "
"unit_conversion.SpeedConverter instead",
(
"uses speed utility. This is deprecated since 2022.10 and will "
"stop working in Home Assistant 2023.4, it should be updated to use "
"unit_conversion.SpeedConverter instead"
),
error_if_core=False,
)
return SpeedConverter.convert(value, from_unit, to_unit)

View file

@ -39,9 +39,11 @@ def convert(
) -> float:
"""Convert a temperature from one unit to another."""
report(
"uses temperature utility. This is deprecated since 2022.10 and will "
"stop working in Home Assistant 2023.4, it should be updated to use "
"unit_conversion.TemperatureConverter instead",
(
"uses temperature utility. This is deprecated since 2022.10 and will "
"stop working in Home Assistant 2023.4, it should be updated to use "
"unit_conversion.TemperatureConverter instead"
),
error_if_core=False,
)
if interval:

View file

@ -125,9 +125,11 @@ class UnitSystem:
def name(self) -> str:
"""Return the name of the unit system."""
report(
"accesses the `name` property of the unit system. "
"This is deprecated and will stop working in Home Assistant 2023.1. "
"Please adjust to use instance check instead.",
(
"accesses the `name` property of the unit system. "
"This is deprecated and will stop working in Home Assistant 2023.1. "
"Please adjust to use instance check instead."
),
error_if_core=False,
)
if self is IMPERIAL_SYSTEM:
@ -139,9 +141,11 @@ class UnitSystem:
def is_metric(self) -> bool:
"""Determine if this is the metric unit system."""
report(
"accesses the `is_metric` property of the unit system. "
"This is deprecated and will stop working in Home Assistant 2023.1. "
"Please adjust to use instance check instead.",
(
"accesses the `is_metric` property of the unit system. "
"This is deprecated and will stop working in Home Assistant 2023.1. "
"Please adjust to use instance check instead."
),
error_if_core=False,
)
return self is METRIC_SYSTEM

View file

@ -42,9 +42,11 @@ def cubic_feet_to_cubic_meter(cubic_feet: float) -> float:
def convert(volume: float, from_unit: str, to_unit: str) -> float:
"""Convert a volume from one unit to another."""
report(
"uses volume utility. This is deprecated since 2022.10 and will "
"stop working in Home Assistant 2023.4, it should be updated to use "
"unit_conversion.VolumeConverter instead",
(
"uses volume utility. This is deprecated since 2022.10 and will "
"stop working in Home Assistant 2023.4, it should be updated to use "
"unit_conversion.VolumeConverter instead"
),
error_if_core=False,
)
return VolumeConverter.convert(volume, from_unit, to_unit)

View file

@ -85,7 +85,10 @@ class Secrets:
_LOGGER.setLevel(logging.DEBUG)
else:
_LOGGER.error(
"Error in secrets.yaml: 'logger: debug' expected, but 'logger: %s' found",
(
"Error in secrets.yaml: 'logger: debug' expected, but"
" 'logger: %s' found"
),
logger,
)
del secrets["logger"]