Make UnitSystem a frozen dataclass (#140954)

* Make UnitSystem a frozen dataclass

* Use super() for attribute setting in UnitSystem class
This commit is contained in:
Shay Levy 2025-03-25 12:45:54 +02:00 committed by GitHub
parent 3766040960
commit 32a16ae0f0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -2,6 +2,7 @@
from __future__ import annotations from __future__ import annotations
from dataclasses import dataclass
from numbers import Number from numbers import Number
from typing import TYPE_CHECKING, Final from typing import TYPE_CHECKING, Final
@ -82,9 +83,21 @@ def _is_valid_unit(unit: str, unit_type: str) -> bool:
return False return False
@dataclass(frozen=True, kw_only=True)
class UnitSystem: class UnitSystem:
"""A container for units of measure.""" """A container for units of measure."""
_name: str
accumulated_precipitation_unit: UnitOfPrecipitationDepth
area_unit: UnitOfArea
length_unit: UnitOfLength
mass_unit: UnitOfMass
pressure_unit: UnitOfPressure
temperature_unit: UnitOfTemperature
volume_unit: UnitOfVolume
wind_speed_unit: UnitOfSpeed
_conversions: dict[tuple[SensorDeviceClass | str | None, str | None], str]
def __init__( def __init__(
self, self,
name: str, name: str,
@ -118,16 +131,16 @@ class UnitSystem:
if errors: if errors:
raise ValueError(errors) raise ValueError(errors)
self._name = name super().__setattr__("_name", name)
self.accumulated_precipitation_unit = accumulated_precipitation super().__setattr__("accumulated_precipitation_unit", accumulated_precipitation)
self.area_unit = area super().__setattr__("area_unit", area)
self.length_unit = length super().__setattr__("length_unit", length)
self.mass_unit = mass super().__setattr__("mass_unit", mass)
self.pressure_unit = pressure super().__setattr__("pressure_unit", pressure)
self.temperature_unit = temperature super().__setattr__("temperature_unit", temperature)
self.volume_unit = volume super().__setattr__("volume_unit", volume)
self.wind_speed_unit = wind_speed super().__setattr__("wind_speed_unit", wind_speed)
self._conversions = conversions super().__setattr__("_conversions", conversions)
def temperature(self, temperature: float, from_unit: str) -> float: def temperature(self, temperature: float, from_unit: str) -> float:
"""Convert the given temperature to this unit system.""" """Convert the given temperature to this unit system."""