Skip to content

Commit

Permalink
Beautify code with ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
Limych committed Oct 7, 2024
1 parent 9513713 commit 042086e
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 34 deletions.
3 changes: 2 additions & 1 deletion custom_components/apparent_temperature/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Custom component to calculate air temperature feeling.
"""
Custom component to calculate air temperature feeling.
For more details about this integration, please refer to
https://github.com/Limych/ha-temperature-feeling
Expand Down
46 changes: 26 additions & 20 deletions custom_components/apparent_temperature/sensor.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
"""Sensor platform for apparent_temperature."""

from collections.abc import Callable
import logging
import math
from collections.abc import Mapping
from typing import Any

import voluptuous as vol

from homeassistant.components.climate import (
ATTR_CURRENT_HUMIDITY,
ATTR_CURRENT_TEMPERATURE,
)
from homeassistant.components.climate import (
DOMAIN as CLIMATE_DOMAIN,
)
from homeassistant.components.group import expand_entity_ids
Expand All @@ -23,6 +25,8 @@
ATTR_WEATHER_TEMPERATURE_UNIT,
ATTR_WEATHER_WIND_SPEED,
ATTR_WEATHER_WIND_SPEED_UNIT,
)
from homeassistant.components.weather import (
DOMAIN as WEATHER_DOMAIN,
)
from homeassistant.const import (
Expand All @@ -40,15 +44,15 @@
)
from homeassistant.core import (
Event,
EventStateChangedData,
HomeAssistant,
State,
callback,
split_entity_id,
)
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.event import async_track_state_change_event
from homeassistant.helpers.typing import ConfigType
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType, UndefinedType
from homeassistant.util.unit_conversion import SpeedConverter, TemperatureConverter

from .const import (
Expand Down Expand Up @@ -76,9 +80,9 @@
async def async_setup_platform(
hass: HomeAssistant,
config: ConfigType,
async_add_entities: Callable,
discovery_info=None,
):
async_add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None, # noqa: ARG001
) -> None:
"""Set up the Car Wash sensor."""
# Print startup message
_LOGGER.info(STARTUP_MESSAGE)
Expand Down Expand Up @@ -133,15 +137,15 @@ def _compose_name(source_name: str) -> str:
)

@property
def name(self):
def name(self) -> str | UndefinedType | None:
"""Return the name of the sensor."""
if self._name:
return self._name

return self._compose_name(split_entity_id(self._sources[0])[1])

@property
def extra_state_attributes(self):
def extra_state_attributes(self) -> Mapping[str, Any] | None:
"""Return entity specific state attributes."""
return {
ATTR_TEMPERATURE_SOURCE: self._temp,
Expand Down Expand Up @@ -197,29 +201,31 @@ def _setup_sources(self) -> list[str]:

return list(entities)

async def async_added_to_hass(self):
async def async_added_to_hass(self) -> None:
"""Register callbacks."""

# pylint: disable=unused-argument
@callback
def sensor_state_listener(event: Event[EventStateChangedData]) -> None:
def sensor_state_listener(event: Event) -> None: # noqa: ARG001
"""Handle device state changes."""
self.async_schedule_update_ha_state(True)
self.async_schedule_update_ha_state(force_refresh=True)

# pylint: disable=unused-argument
@callback
def sensor_startup(event):
def sensor_startup(event: Event) -> None: # noqa: ARG001
"""Update entity on startup."""
async_track_state_change_event(
self.hass, self._setup_sources(), sensor_state_listener
)

self.async_schedule_update_ha_state(True) # Force first update
self.async_schedule_update_ha_state(
force_refresh=True
) # Force first update

self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, sensor_startup)

@staticmethod
def _has_state(state) -> bool:
def _has_state(state: str | None) -> bool:
"""Return True if state has any value."""
return state is not None and state not in [
STATE_UNKNOWN,
Expand Down Expand Up @@ -254,8 +260,8 @@ def _get_temperature(self, entity_id: str | None) -> float | None:
temperature = TemperatureConverter.convert(
float(temperature), entity_unit, UnitOfTemperature.CELSIUS
)
except ValueError as exc:
_LOGGER.error('Could not convert value "%s" to float: %s', state, exc)
except ValueError:
_LOGGER.exception('Could not convert value "%s" to float', state)
return None

return float(temperature)
Expand Down Expand Up @@ -304,13 +310,13 @@ def _get_wind_speed(self, entity_id: str | None) -> float | None:
wind_speed = SpeedConverter.convert(
float(wind_speed), entity_unit, UnitOfSpeed.METERS_PER_SECOND
)
except ValueError as exc:
_LOGGER.error('Could not convert value "%s" to float: %s', state, exc)
except ValueError:
_LOGGER.exception('Could not convert value "%s" to float', state)
return None

return float(wind_speed)

async def async_update(self):
async def async_update(self) -> None:
"""Update sensor state."""
self._temp_val = temp = self._get_temperature(self._temp) # °C
self._humd_val = humd = self._get_humidity(self._humd) # %
Expand Down
27 changes: 14 additions & 13 deletions tests/test_sensor.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,9 @@
# pylint: disable=protected-access,redefined-outer-name
"""The test for the sensor platform."""

from typing import Final

import pytest
from pytest_homeassistant_custom_component.common import assert_setup_component

from custom_components.apparent_temperature.const import (
ATTR_HUMIDITY_SOURCE,
ATTR_HUMIDITY_SOURCE_VALUE,
ATTR_TEMPERATURE_SOURCE,
ATTR_TEMPERATURE_SOURCE_VALUE,
ATTR_WIND_SPEED_SOURCE,
ATTR_WIND_SPEED_SOURCE_VALUE,
DOMAIN,
)
from custom_components.apparent_temperature.sensor import ApparentTemperatureSensor
from homeassistant.components.number import NumberDeviceClass
from homeassistant.components.sensor import SensorStateClass
from homeassistant.components.weather import (
Expand All @@ -33,6 +22,18 @@
)
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from pytest_homeassistant_custom_component.common import assert_setup_component

from custom_components.apparent_temperature.const import (
ATTR_HUMIDITY_SOURCE,
ATTR_HUMIDITY_SOURCE_VALUE,
ATTR_TEMPERATURE_SOURCE,
ATTR_TEMPERATURE_SOURCE_VALUE,
ATTR_WIND_SPEED_SOURCE,
ATTR_WIND_SPEED_SOURCE_VALUE,
DOMAIN,
)
from custom_components.apparent_temperature.sensor import ApparentTemperatureSensor

TEST_UNIQUE_ID: Final = "test_id"
TEST_NAME: Final = "test_name"
Expand Down Expand Up @@ -244,7 +245,7 @@ async def test_entity_initialization(hass: HomeAssistant):


@pytest.mark.parametrize(
"temp, humi, wind, expected",
("temp", "humi", "wind", "expected"),
[
(12, 32, 10, "7.36460604026573"),
(20, 0, 0, "15.75"),
Expand Down

0 comments on commit 042086e

Please sign in to comment.