From cf5fca0464b47feb58fb29c4ea1c97d1d9f6a359 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Mon, 9 Jan 2023 00:40:08 +0100 Subject: [PATCH] Code styling tweaks to core entity components (#85460) --- homeassistant/components/calendar/trigger.py | 7 ++++--- homeassistant/components/camera/img_util.py | 5 ++++- homeassistant/components/light/__init__.py | 11 ++++++----- .../components/media_player/__init__.py | 3 ++- .../components/media_player/browse_media.py | 5 +++-- homeassistant/components/number/__init__.py | 8 ++++++-- homeassistant/components/sensor/__init__.py | 16 +++++++++------- homeassistant/components/sensor/recorder.py | 17 ++++++++++++++--- homeassistant/components/stt/__init__.py | 3 ++- homeassistant/components/tts/__init__.py | 15 ++++++++++++--- homeassistant/components/update/__init__.py | 8 ++++---- homeassistant/components/update/recorder.py | 2 +- homeassistant/components/weather/__init__.py | 8 ++++++-- 13 files changed, 73 insertions(+), 35 deletions(-) diff --git a/homeassistant/components/calendar/trigger.py b/homeassistant/components/calendar/trigger.py index 0fdb7259c9d..1e51c746e18 100644 --- a/homeassistant/components/calendar/trigger.py +++ b/homeassistant/components/calendar/trigger.py @@ -84,9 +84,10 @@ class CalendarEventListener: async def _fetch_events(self, last_endtime: datetime.datetime) -> None: """Update the set of eligible events.""" - # Use a sliding window for selecting in scope events in the next interval. The event - # search range is offset, then the fire time of the returned events are offset again below. - # Event time ranges are exclusive so the end time is expanded by 1sec + # Use a sliding window for selecting in scope events in the next interval. + # The event search range is offset, then the fire time of the returned events + # are offset again below. Event time ranges are exclusive so the end time + # is expanded by 1sec. start_time = last_endtime - self._offset end_time = start_time + UPDATE_INTERVAL + datetime.timedelta(seconds=1) _LOGGER.debug( diff --git a/homeassistant/components/camera/img_util.py b/homeassistant/components/camera/img_util.py index 3aadc5c454c..87bc0e14fba 100644 --- a/homeassistant/components/camera/img_util.py +++ b/homeassistant/components/camera/img_util.py @@ -38,7 +38,10 @@ def find_supported_scaling_factor( def scale_jpeg_camera_image(cam_image: Image, width: int, height: int) -> bytes: - """Scale a camera image as close as possible to one of the supported scaling factors.""" + """Scale a camera image. + + Scale as close as possible to one of the supported scaling factors. + """ turbo_jpeg = TurboJPEGSingleton.instance() if not turbo_jpeg: return cam_image.content diff --git a/homeassistant/components/light/__init__.py b/homeassistant/components/light/__init__.py index acc6252d3b3..24368ccc1a3 100644 --- a/homeassistant/components/light/__init__.py +++ b/homeassistant/components/light/__init__.py @@ -434,9 +434,8 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: # noqa: ): profiles.apply_default(light.entity_id, light.is_on, params) - legacy_supported_color_modes = ( - light._light_internal_supported_color_modes # pylint: disable=protected-access - ) + # pylint: disable=protected-access + legacy_supported_color_modes = light._light_internal_supported_color_modes supported_color_modes = light.supported_color_modes # If a color temperature is specified, emulate it if not supported by the light @@ -504,8 +503,10 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: # noqa: params[ATTR_RGBW_COLOR] = color_util.color_rgb_to_rgbw(*rgb_color) elif ColorMode.RGBWW in supported_color_modes: # https://github.com/python/mypy/issues/13673 - params[ATTR_RGBWW_COLOR] = color_util.color_rgb_to_rgbww( # type: ignore[call-arg] - *rgb_color, light.min_color_temp_kelvin, light.max_color_temp_kelvin + params[ATTR_RGBWW_COLOR] = color_util.color_rgb_to_rgbww( + *rgb_color, # type: ignore[call-arg] + light.min_color_temp_kelvin, + light.max_color_temp_kelvin, ) elif ColorMode.HS in supported_color_modes: params[ATTR_HS_COLOR] = color_util.color_RGB_to_hs(*rgb_color) diff --git a/homeassistant/components/media_player/__init__.py b/homeassistant/components/media_player/__init__.py index fa2c5465443..341c9468d11 100644 --- a/homeassistant/components/media_player/__init__.py +++ b/homeassistant/components/media_player/__init__.py @@ -1201,7 +1201,8 @@ async def websocket_browse_media( """ Browse media available to the media_player entity. - To use, media_player integrations can implement MediaPlayerEntity.async_browse_media() + To use, media_player integrations can implement + MediaPlayerEntity.async_browse_media() """ component: EntityComponent[MediaPlayerEntity] = hass.data[DOMAIN] player = component.get_entity(msg["entity_id"]) diff --git a/homeassistant/components/media_player/browse_media.py b/homeassistant/components/media_player/browse_media.py index 81ded203e75..d1328a851d2 100644 --- a/homeassistant/components/media_player/browse_media.py +++ b/homeassistant/components/media_player/browse_media.py @@ -51,8 +51,9 @@ def async_process_play_media_url( "Not signing path for content with query param" ) elif parsed.path.startswith(PATHS_WITHOUT_AUTH): - # We don't sign this path if it doesn't need auth. Although signing itself can't hurt, - # some devices are unable to handle long URLs and the auth signature might push it over. + # We don't sign this path if it doesn't need auth. Although signing itself can't + # hurt, some devices are unable to handle long URLs and the auth signature might + # push it over. pass else: signed_path = async_sign_path( diff --git a/homeassistant/components/number/__init__.py b/homeassistant/components/number/__init__.py index 2c4794619da..e4ed8bb1d3e 100644 --- a/homeassistant/components/number/__init__.py +++ b/homeassistant/components/number/__init__.py @@ -424,7 +424,9 @@ class NumberEntityDescription(EntityDescription): or self.step is not None or self.unit_of_measurement is not None ): - if self.__class__.__name__ == "NumberEntityDescription": # type: ignore[unreachable] + if ( # type: ignore[unreachable] + self.__class__.__name__ == "NumberEntityDescription" + ): caller = inspect.stack()[2] module = inspect.getmodule(caller[0]) else: @@ -668,7 +670,9 @@ class NumberEntity(Entity): hasattr(self, "entity_description") and self.entity_description.unit_of_measurement is not None ): - return self.entity_description.unit_of_measurement # type: ignore[unreachable] + return ( # type: ignore[unreachable] + self.entity_description.unit_of_measurement + ) native_unit_of_measurement = self.native_unit_of_measurement diff --git a/homeassistant/components/sensor/__init__.py b/homeassistant/components/sensor/__init__.py index 067adb12817..4a5ff3de893 100644 --- a/homeassistant/components/sensor/__init__.py +++ b/homeassistant/components/sensor/__init__.py @@ -12,7 +12,9 @@ from math import floor, log10 from typing import Any, Final, cast, final from homeassistant.config_entries import ConfigEntry -from homeassistant.const import ( # noqa: F401, pylint: disable=[hass-deprecated-import] + +# pylint: disable=[hass-deprecated-import] +from homeassistant.const import ( # noqa: F401 CONF_UNIT_OF_MEASUREMENT, DEVICE_CLASS_AQI, DEVICE_CLASS_BATTERY, @@ -350,12 +352,12 @@ class SensorEntity(Entity): For sensors without a `unique_id`, this takes precedence over legacy temperature conversion rules only. - For sensors with a `unique_id`, this is applied only if the unit is not set by the user, - and takes precedence over automatic device-class conversion rules. + For sensors with a `unique_id`, this is applied only if the unit is not set by + the user, and takes precedence over automatic device-class conversion rules. Note: - suggested_unit_of_measurement is stored in the entity registry the first time - the entity is seen, and then never updated. + suggested_unit_of_measurement is stored in the entity registry the first + time the entity is seen, and then never updated. """ if hasattr(self, "_attr_suggested_unit_of_measurement"): return self._attr_suggested_unit_of_measurement @@ -367,8 +369,8 @@ class SensorEntity(Entity): @property def unit_of_measurement(self) -> str | None: """Return the unit of measurement of the entity, after unit conversion.""" - # Highest priority, for registered entities: unit set by user, with fallback to unit suggested - # by integration or secondary fallback to unit conversion rules + # Highest priority, for registered entities: unit set by user,with fallback to + # unit suggested by integration or secondary fallback to unit conversion rules if self._sensor_option_unit_of_measurement: return self._sensor_option_unit_of_measurement diff --git a/homeassistant/components/sensor/recorder.py b/homeassistant/components/sensor/recorder.py index 412ea3d4d5d..5224514f0e4 100644 --- a/homeassistant/components/sensor/recorder.py +++ b/homeassistant/components/sensor/recorder.py @@ -507,9 +507,19 @@ def _compile_statistics( # noqa: C901 # Make calculations stat: StatisticData = {"start": start} if "max" in wanted_statistics[entity_id]: - stat["max"] = max(*itertools.islice(zip(*fstates), 1)) # type: ignore[typeddict-item] + stat["max"] = max( + *itertools.islice( + zip(*fstates), # type: ignore[typeddict-item] + 1, + ) + ) if "min" in wanted_statistics[entity_id]: - stat["min"] = min(*itertools.islice(zip(*fstates), 1)) # type: ignore[typeddict-item] + stat["min"] = min( + *itertools.islice( + zip(*fstates), # type: ignore[typeddict-item] + 1, + ) + ) if "mean" in wanted_statistics[entity_id]: stat["mean"] = _time_weighted_average(fstates, start, end) @@ -519,7 +529,8 @@ def _compile_statistics( # noqa: C901 new_state = old_state = None _sum = 0.0 if entity_id in last_stats: - # We have compiled history for this sensor before, use that as a starting point + # We have compiled history for this sensor before, + # use that as a starting point. last_reset = old_last_reset = last_stats[entity_id][0]["last_reset"] if old_last_reset is not None: last_reset = old_last_reset = old_last_reset.isoformat() diff --git a/homeassistant/components/stt/__init__.py b/homeassistant/components/stt/__init__.py index 1d68b0a954b..94e08d25363 100644 --- a/homeassistant/components/stt/__init__.py +++ b/homeassistant/components/stt/__init__.py @@ -231,7 +231,8 @@ class SpeechToTextView(HomeAssistantView): def metadata_from_header(request: web.Request) -> SpeechMetadata: """Extract STT metadata from header. - X-Speech-Content: format=wav; codec=pcm; sample_rate=16000; bit_rate=16; channel=1; language=de_de + X-Speech-Content: + format=wav; codec=pcm; sample_rate=16000; bit_rate=16; channel=1; language=de_de """ try: data = request.headers[istr("X-Speech-Content")].split(";") diff --git a/homeassistant/components/tts/__init__.py b/homeassistant/components/tts/__init__.py index c07df07ae4f..b08487fc842 100644 --- a/homeassistant/components/tts/__init__.py +++ b/homeassistant/components/tts/__init__.py @@ -621,9 +621,18 @@ class SpeechManager: if not tts_file.tags: tts_file.add_tags() if isinstance(tts_file.tags, ID3): - tts_file["artist"] = ID3Text(encoding=3, text=artist) # type: ignore[no-untyped-call] - tts_file["album"] = ID3Text(encoding=3, text=album) # type: ignore[no-untyped-call] - tts_file["title"] = ID3Text(encoding=3, text=message) # type: ignore[no-untyped-call] + tts_file["artist"] = ID3Text( + encoding=3, + text=artist, # type: ignore[no-untyped-call] + ) + tts_file["album"] = ID3Text( + encoding=3, + text=album, # type: ignore[no-untyped-call] + ) + tts_file["title"] = ID3Text( + encoding=3, + text=message, # type: ignore[no-untyped-call] + ) else: tts_file["artist"] = artist tts_file["album"] = album diff --git a/homeassistant/components/update/__init__.py b/homeassistant/components/update/__init__.py index f8d00300d81..09207665748 100644 --- a/homeassistant/components/update/__init__.py +++ b/homeassistant/components/update/__init__.py @@ -326,16 +326,16 @@ class UpdateEntity(RestoreEntity): async def async_release_notes(self) -> str | None: """Return full release notes. - This is suitable for a long changelog that does not fit in the release_summary property. - The returned string can contain markdown. + This is suitable for a long changelog that does not fit in the release_summary + property. The returned string can contain markdown. """ return await self.hass.async_add_executor_job(self.release_notes) def release_notes(self) -> str | None: """Return full release notes. - This is suitable for a long changelog that does not fit in the release_summary property. - The returned string can contain markdown. + This is suitable for a long changelog that does not fit in the release_summary + property. The returned string can contain markdown. """ raise NotImplementedError() diff --git a/homeassistant/components/update/recorder.py b/homeassistant/components/update/recorder.py index 1b22360761f..408937c4f31 100644 --- a/homeassistant/components/update/recorder.py +++ b/homeassistant/components/update/recorder.py @@ -9,5 +9,5 @@ from .const import ATTR_IN_PROGRESS, ATTR_RELEASE_SUMMARY @callback def exclude_attributes(hass: HomeAssistant) -> set[str]: - """Exclude large and chatty update attributes from being recorded in the database.""" + """Exclude large and chatty update attributes from being recorded.""" return {ATTR_ENTITY_PICTURE, ATTR_IN_PROGRESS, ATTR_RELEASE_SUMMARY} diff --git a/homeassistant/components/weather/__init__.py b/homeassistant/components/weather/__init__.py index fcfba179cd7..52642c4f1bf 100644 --- a/homeassistant/components/weather/__init__.py +++ b/homeassistant/components/weather/__init__.py @@ -157,7 +157,8 @@ def round_temperature(temperature: float | None, precision: float) -> float | No class Forecast(TypedDict, total=False): """Typed weather forecast dict. - All attributes are in native units and old attributes kept for backwards compatibility. + All attributes are in native units and old attributes kept + for backwards compatibility. """ condition: str | None @@ -622,7 +623,10 @@ class WeatherEntity(Entity): @final @property def state_attributes(self) -> dict[str, Any]: - """Return the state attributes, converted from native units to user-configured units.""" + """Return the state attributes, converted. + + Attributes are configured from native units to user-configured units. + """ data: dict[str, Any] = {} precision = self.precision