Improve native_value type hints in integrations (#90033)

This commit is contained in:
epenet 2023-03-21 11:40:06 +01:00 committed by GitHub
parent 0e1c76f81f
commit 86b4354477
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 35 additions and 31 deletions

View File

@ -1,11 +1,11 @@
"""The FiveM sensor platform.""" """The FiveM sensor platform."""
from dataclasses import dataclass from dataclasses import dataclass
from typing import Any
from homeassistant.components.sensor import SensorEntity, SensorEntityDescription from homeassistant.components.sensor import SensorEntity, SensorEntityDescription
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import StateType
from . import FiveMEntity, FiveMEntityDescription from . import FiveMEntity, FiveMEntityDescription
from .const import ( from .const import (
@ -73,6 +73,6 @@ class FiveMSensorEntity(FiveMEntity, SensorEntity):
entity_description: FiveMSensorEntityDescription entity_description: FiveMSensorEntityDescription
@property @property
def native_value(self) -> Any: def native_value(self) -> StateType:
"""Return the state of the sensor.""" """Return the state of the sensor."""
return self.coordinator.data[self.entity_description.key] return self.coordinator.data[self.entity_description.key]

View File

@ -3,7 +3,6 @@ from __future__ import annotations
from collections.abc import Callable from collections.abc import Callable
from dataclasses import dataclass from dataclasses import dataclass
from typing import Any
from homeassistant.components.sensor import ( from homeassistant.components.sensor import (
SensorDeviceClass, SensorDeviceClass,
@ -15,6 +14,7 @@ from homeassistant.config_entries import ConfigEntry
from homeassistant.const import PERCENTAGE, EntityCategory, UnitOfInformation from homeassistant.const import PERCENTAGE, EntityCategory, UnitOfInformation
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import StateType
from .const import DOMAIN from .const import DOMAIN
from .coordinator import FullyKioskDataUpdateCoordinator from .coordinator import FullyKioskDataUpdateCoordinator
@ -30,7 +30,7 @@ def round_storage(value: int) -> float:
class FullySensorEntityDescription(SensorEntityDescription): class FullySensorEntityDescription(SensorEntityDescription):
"""Fully Kiosk Browser sensor description.""" """Fully Kiosk Browser sensor description."""
state_fn: Callable | None = None state_fn: Callable[[int], float] | None = None
SENSORS: tuple[FullySensorEntityDescription, ...] = ( SENSORS: tuple[FullySensorEntityDescription, ...] = (
@ -130,7 +130,7 @@ class FullySensor(FullyKioskEntity, SensorEntity):
super().__init__(coordinator) super().__init__(coordinator)
@property @property
def native_value(self) -> Any: def native_value(self) -> StateType:
"""Return the state of the sensor.""" """Return the state of the sensor."""
if (value := self.coordinator.data.get(self.entity_description.key)) is None: if (value := self.coordinator.data.get(self.entity_description.key)) is None:
return None return None
@ -138,4 +138,4 @@ class FullySensor(FullyKioskEntity, SensorEntity):
if self.entity_description.state_fn is not None: if self.entity_description.state_fn is not None:
return self.entity_description.state_fn(value) return self.entity_description.state_fn(value)
return value return value # type: ignore[no-any-return]

View File

@ -24,6 +24,7 @@ from homeassistant.const import (
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import StateType
from homeassistant.helpers.update_coordinator import CoordinatorEntity from homeassistant.helpers.update_coordinator import CoordinatorEntity
from .const import DOMAIN from .const import DOMAIN
@ -791,7 +792,7 @@ class PlenticoreDataSensor(
return f"{self.platform_name} {self._sensor_name}" return f"{self.platform_name} {self._sensor_name}"
@property @property
def native_value(self) -> Any | None: def native_value(self) -> StateType:
"""Return the state of the sensor.""" """Return the state of the sensor."""
if self.coordinator.data is None: if self.coordinator.data is None:
# None is translated to STATE_UNKNOWN # None is translated to STATE_UNKNOWN

View File

@ -20,6 +20,7 @@ from homeassistant.const import (
) )
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import StateType
from homeassistant.helpers.update_coordinator import ( from homeassistant.helpers.update_coordinator import (
CoordinatorEntity, CoordinatorEntity,
DataUpdateCoordinator, DataUpdateCoordinator,
@ -207,7 +208,7 @@ class MetOfficeCurrentSensor(
) )
@property @property
def native_value(self) -> Any | None: def native_value(self) -> StateType:
"""Return the state of the sensor.""" """Return the state of the sensor."""
value = None value = None

View File

@ -3,14 +3,12 @@ from __future__ import annotations
import logging import logging
from voluptuous.validators import Number
from homeassistant.components.sensor import SensorDeviceClass, SensorEntity from homeassistant.components.sensor import SensorDeviceClass, SensorEntity
from homeassistant.const import PERCENTAGE, UnitOfLength from homeassistant.const import PERCENTAGE, UnitOfLength
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.icon import icon_for_battery_level from homeassistant.helpers.icon import icon_for_battery_level
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType, StateType
from homeassistant.util.unit_conversion import DistanceConverter from homeassistant.util.unit_conversion import DistanceConverter
from homeassistant.util.unit_system import US_CUSTOMARY_SYSTEM from homeassistant.util.unit_system import US_CUSTOMARY_SYSTEM
@ -63,11 +61,11 @@ class LeafBatterySensor(LeafEntity, SensorEntity):
return f"{self.car.leaf.nickname} Charge" return f"{self.car.leaf.nickname} Charge"
@property @property
def native_value(self) -> Number | None: def native_value(self) -> StateType:
"""Battery state percentage.""" """Battery state percentage."""
if self.car.data[DATA_BATTERY] is None: if self.car.data[DATA_BATTERY] is None:
return None return None
return round(self.car.data[DATA_BATTERY]) return round(self.car.data[DATA_BATTERY]) # type: ignore[no-any-return]
@property @property
def icon(self) -> str: def icon(self) -> str:

View File

@ -1,8 +1,6 @@
"""Support for getting statistical data from a Pi-hole system.""" """Support for getting statistical data from a Pi-hole system."""
from __future__ import annotations from __future__ import annotations
from typing import Any
from hole import Hole from hole import Hole
from homeassistant.components.sensor import SensorEntity, SensorEntityDescription from homeassistant.components.sensor import SensorEntity, SensorEntityDescription
@ -10,6 +8,7 @@ from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_NAME, PERCENTAGE from homeassistant.const import CONF_NAME, PERCENTAGE
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import StateType
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
from . import PiHoleEntity from . import PiHoleEntity
@ -113,9 +112,9 @@ class PiHoleSensor(PiHoleEntity, SensorEntity):
self._attr_unique_id = f"{self._server_unique_id}/{description.name}" self._attr_unique_id = f"{self._server_unique_id}/{description.name}"
@property @property
def native_value(self) -> Any: def native_value(self) -> StateType:
"""Return the state of the device.""" """Return the state of the device."""
try: try:
return round(self.api.data[self.entity_description.key], 2) return round(self.api.data[self.entity_description.key], 2) # type: ignore[no-any-return]
except TypeError: except TypeError:
return self.api.data[self.entity_description.key] return self.api.data[self.entity_description.key] # type: ignore[no-any-return]

View File

@ -3,7 +3,6 @@ from __future__ import annotations
from dataclasses import dataclass from dataclasses import dataclass
from datetime import datetime, timedelta from datetime import datetime, timedelta
from typing import Any
from synology_dsm.api.core.utilization import SynoCoreUtilization from synology_dsm.api.core.utilization import SynoCoreUtilization
from synology_dsm.api.dsm.information import SynoDSMInformation from synology_dsm.api.dsm.information import SynoDSMInformation
@ -26,6 +25,7 @@ from homeassistant.const import (
) )
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import StateType
from homeassistant.util.dt import utcnow from homeassistant.util.dt import utcnow
from . import SynoApi from . import SynoApi
@ -349,7 +349,7 @@ class SynoDSMUtilSensor(SynoDSMSensor):
"""Representation a Synology Utilisation sensor.""" """Representation a Synology Utilisation sensor."""
@property @property
def native_value(self) -> Any | None: def native_value(self) -> StateType:
"""Return the state.""" """Return the state."""
attr = getattr(self._api.utilisation, self.entity_description.key) attr = getattr(self._api.utilisation, self.entity_description.key)
if callable(attr): if callable(attr):
@ -357,19 +357,23 @@ class SynoDSMUtilSensor(SynoDSMSensor):
if attr is None: if attr is None:
return None return None
result: StateType = attr
# Data (RAM) # Data (RAM)
if self.native_unit_of_measurement == UnitOfInformation.MEGABYTES: if self.native_unit_of_measurement == UnitOfInformation.MEGABYTES:
return round(attr / 1024.0**2, 1) result = round(attr / 1024.0**2, 1)
return result
# Network # Network
if self.native_unit_of_measurement == UnitOfDataRate.KILOBYTES_PER_SECOND: if self.native_unit_of_measurement == UnitOfDataRate.KILOBYTES_PER_SECOND:
return round(attr / 1024.0, 1) result = round(attr / 1024.0, 1)
return result
# CPU load average # CPU load average
if self.native_unit_of_measurement == ENTITY_UNIT_LOAD: if self.native_unit_of_measurement == ENTITY_UNIT_LOAD:
return round(attr / 100, 2) result = round(attr / 100, 2)
return result
return attr return result
@property @property
def available(self) -> bool: def available(self) -> bool:
@ -393,7 +397,7 @@ class SynoDSMStorageSensor(SynologyDSMDeviceEntity, SynoDSMSensor):
super().__init__(api, coordinator, description, device_id) super().__init__(api, coordinator, description, device_id)
@property @property
def native_value(self) -> Any | None: def native_value(self) -> StateType:
"""Return the state.""" """Return the state."""
attr = getattr(self._api.storage, self.entity_description.key)(self._device_id) attr = getattr(self._api.storage, self.entity_description.key)(self._device_id)
if attr is None: if attr is None:
@ -401,9 +405,9 @@ class SynoDSMStorageSensor(SynologyDSMDeviceEntity, SynoDSMSensor):
# Data (disk space) # Data (disk space)
if self.native_unit_of_measurement == UnitOfInformation.TERABYTES: if self.native_unit_of_measurement == UnitOfInformation.TERABYTES:
return round(attr / 1024.0**4, 2) return round(attr / 1024.0**4, 2) # type: ignore[no-any-return]
return attr return attr # type: ignore[no-any-return]
class SynoDSMInfoSensor(SynoDSMSensor): class SynoDSMInfoSensor(SynoDSMSensor):
@ -421,7 +425,7 @@ class SynoDSMInfoSensor(SynoDSMSensor):
self._last_boot: datetime | None = None self._last_boot: datetime | None = None
@property @property
def native_value(self) -> Any | None: def native_value(self) -> StateType | datetime:
"""Return the state.""" """Return the state."""
attr = getattr(self._api.information, self.entity_description.key) attr = getattr(self._api.information, self.entity_description.key)
if attr is None: if attr is None:
@ -434,4 +438,4 @@ class SynoDSMInfoSensor(SynoDSMSensor):
self._previous_uptime = attr self._previous_uptime = attr
return self._last_boot return self._last_boot
return attr return attr # type: ignore[no-any-return]

View File

@ -41,6 +41,7 @@ from homeassistant.helpers.device_registry import async_get as async_get_dev_reg
from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.entity_registry import async_get as async_get_entity_reg from homeassistant.helpers.entity_registry import async_get as async_get_entity_reg
from homeassistant.helpers.typing import StateType
from homeassistant.helpers.update_coordinator import ( from homeassistant.helpers.update_coordinator import (
CoordinatorEntity, CoordinatorEntity,
DataUpdateCoordinator, DataUpdateCoordinator,
@ -426,9 +427,9 @@ class TibberDataSensor(TibberSensor, CoordinatorEntity["TibberDataCoordinator"])
self._device_name = self._home_name self._device_name = self._home_name
@property @property
def native_value(self) -> Any: def native_value(self) -> StateType:
"""Return the value of the sensor.""" """Return the value of the sensor."""
return getattr(self._tibber_home, self.entity_description.key) return getattr(self._tibber_home, self.entity_description.key) # type: ignore[no-any-return]
class TibberSensorRT(TibberSensor, CoordinatorEntity["TibberRtDataCoordinator"]): class TibberSensorRT(TibberSensor, CoordinatorEntity["TibberRtDataCoordinator"]):