Enable ruff RUF046 rule and remove unnecessary int() casts (#170514)

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Franck Nijhof
2026-05-13 23:50:44 +02:00
committed by GitHub
co-authored by Claude Opus 4.6
parent 0b0618e5c8
commit b3eb97adad
31 changed files with 49 additions and 47 deletions
@@ -470,7 +470,7 @@ async def websocket_device_capture(
# single sample (16 bits) per queue item.
max_queue_items = (
# +1 for None to signal end
int(math.ceil(timeout_seconds * CAPTURE_RATE)) + 1
math.ceil(timeout_seconds * CAPTURE_RATE) + 1
)
audio_queue = DeviceAudioQueue(queue=asyncio.Queue(maxsize=max_queue_items))
@@ -689,7 +689,7 @@ class BluesoundPlayer(CoordinatorEntity[BluesoundCoordinator], MediaPlayerEntity
async def async_set_volume_level(self, volume: float) -> None:
"""Send volume_up command to media player."""
volume = int(round(volume * 100))
volume = round(volume * 100)
volume = min(100, volume)
volume = max(0, volume)
+1 -1
View File
@@ -93,4 +93,4 @@ class DeakoLightEntity(LightEntity):
self._attr_supported_color_modes is not None
and ColorMode.BRIGHTNESS in self._attr_supported_color_modes
):
self._attr_brightness = int(round(state.get("dim", 0) * 2.55))
self._attr_brightness = round(state.get("dim", 0) * 2.55)
@@ -57,7 +57,7 @@ class FressnapfTrackerLight(FressnapfTrackerEntity, LightEntity):
if TYPE_CHECKING:
# The entity is not created if led_brightness_value is None
assert self.coordinator.data.led_brightness_value is not None
return int(round((self.coordinator.data.led_brightness_value / 100) * 255))
return round((self.coordinator.data.led_brightness_value / 100) * 255)
async def async_turn_on(self, **kwargs: Any) -> None:
"""Turn on the device."""
+1 -1
View File
@@ -75,7 +75,7 @@ class GeniusBattery(GeniusDevice, SensorEntity):
icon = "mdi:battery"
if battery_level <= 95:
icon += f"-{int(round(battery_level / 10 - 0.01)) * 10}"
icon += f"-{round(battery_level / 10 - 0.01) * 10}"
return icon
@@ -298,7 +298,7 @@ class HegelMediaPlayer(MediaPlayerEntity):
async def async_set_volume_level(self, volume: float) -> None:
"""Set volume level, range 0..1."""
vol = max(0.0, min(volume, 1.0))
amp_vol = int(round(vol * 100))
amp_vol = round(vol * 100)
try:
await self._client.send(COMMANDS["volume_set"](amp_vol), expect_reply=False)
except (HegelConnectionError, TimeoutError, OSError) as err:
@@ -285,10 +285,10 @@ class HumidifierDehumidifier(HomeAccessory):
"""Return min and max humidity range."""
attributes = state.attributes
min_humidity = max(
int(round(attributes.get(ATTR_MIN_HUMIDITY, DEFAULT_MIN_HUMIDITY))), 0
round(attributes.get(ATTR_MIN_HUMIDITY, DEFAULT_MIN_HUMIDITY)), 0
)
max_humidity = min(
int(round(attributes.get(ATTR_MAX_HUMIDITY, DEFAULT_MAX_HUMIDITY))), 100
round(attributes.get(ATTR_MAX_HUMIDITY, DEFAULT_MAX_HUMIDITY)), 100
)
return min_humidity, max_humidity
@@ -507,14 +507,14 @@ class HomeKitBatterySensor(HomeKitSensor):
icon = "mdi:battery"
is_charging = self.is_charging
if is_charging and native_value > 10:
percentage = int(round(native_value / 20 - 0.01)) * 20
percentage = round(native_value / 20 - 0.01) * 20
icon += f"-charging-{percentage}"
elif is_charging:
icon += "-outline"
elif self.is_low_battery:
icon += "-alert"
elif native_value < 95:
percentage = max(int(round(native_value / 10 - 0.01)) * 10, 10)
percentage = max(round(native_value / 10 - 0.01) * 10, 10)
icon += f"-{percentage}"
return icon
+3 -3
View File
@@ -228,8 +228,8 @@ class HyperionLight(LightEntity):
and not await self._client.async_send_set_adjustment(
**{
const.KEY_ADJUSTMENT: {
const.KEY_BRIGHTNESS: int(
round((float(brightness) * 100) / 255)
const.KEY_BRIGHTNESS: round(
(float(brightness) * 100) / 255
),
const.KEY_ID: item[const.KEY_ID],
}
@@ -295,7 +295,7 @@ class HyperionLight(LightEntity):
if brightness_pct < 0 or brightness_pct > 100:
return
self._set_internal_state(
brightness=int(round((brightness_pct * 255) / float(100)))
brightness=round((brightness_pct * 255) / float(100))
)
self.async_write_ha_state()
+1 -1
View File
@@ -70,7 +70,7 @@ class HassAqualinkLight(AqualinkEntity[AqualinkLight], LightEntity):
await await_or_reraise(self.dev.set_effect_by_name(effect_name))
elif brightness := kwargs.get(ATTR_BRIGHTNESS):
# Aqualink supports percentages in 25% increments.
pct = int(round(brightness * 4.0 / 255)) * 25
pct = round(brightness * 4.0 / 255) * 25
await await_or_reraise(self.dev.set_brightness(pct))
else:
await await_or_reraise(self.dev.turn_on())
+1 -1
View File
@@ -59,7 +59,7 @@ class InsteonCoverEntity(InsteonEntity, CoverEntity):
pos = self._insteon_device_group.value
else:
pos = 0
return int(math.ceil(pos * 100 / 255))
return math.ceil(pos * 100 / 255)
@property
def is_closed(self) -> bool:
+1 -1
View File
@@ -74,7 +74,7 @@ SENSOR_TYPES: list[IOmeterEntityDescription] = [
device_class=SensorDeviceClass.BATTERY,
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda data: (
int(round(data.status.device.core.battery_level))
round(data.status.device.core.battery_level)
if data.status.device.core.battery_level is not None
else None
),
+1 -1
View File
@@ -380,7 +380,7 @@ class LIFXUpdateCoordinator(DataUpdateCoordinator[None]):
if update_rssi:
# We always send the rssi request second
self._rssi = int(floor(10 * log10(responses[1].signal) + 0.5))
self._rssi = floor(10 * log10(responses[1].signal) + 0.5)
if self.is_matrix or self.is_extended_multizone or self.is_legacy_multizone:
self.active_effect = FirmwareEffect[self.device.effect.get("effect", "OFF")]
@@ -55,7 +55,7 @@ WARM_DEVICE_TYPES = {
def to_lutron_level(level):
"""Convert the given Home Assistant light level (0-255) to Lutron (0-100)."""
return int(round((level * 100) / 255))
return round((level * 100) / 255)
def to_hass_level(level):
+2 -2
View File
@@ -212,8 +212,8 @@ class NADtcp(MediaPlayerEntity):
def set_volume_level(self, volume: float) -> None:
"""Set volume level, range 0..1."""
nad_volume_to_set = int(
round(volume * (self._max_vol - self._min_vol) + self._min_vol)
nad_volume_to_set = round(
volume * (self._max_vol - self._min_vol) + self._min_vol
)
self._nad_receiver.set_volume(nad_volume_to_set)
+1 -1
View File
@@ -55,7 +55,7 @@ def get_delay_in_minutes(delay=0):
def get_ride_duration(departure_time: datetime, arrival_time: datetime, delay=0):
"""Calculate the total travel time in minutes."""
duration = arrival_time - departure_time
duration_time = int(round(duration.total_seconds() / 60))
duration_time = round(duration.total_seconds() / 60)
return duration_time + get_delay_in_minutes(delay)
@@ -346,9 +346,7 @@ class SmartThingsLamp(SmartThingsEntity, LightEntity):
# remove 'off' for brightness mapping
if "off" in levels:
levels = [level for level in levels if level != "off"]
level = percentage_to_ordered_list_item(
levels, int(round(brightness * 100 / 255))
)
level = percentage_to_ordered_list_item(levels, round(brightness * 100 / 255))
await self.execute_device_command(
Capability.SAMSUNG_CE_LAMP,
Command.SET_BRIGHTNESS_LEVEL,
@@ -307,7 +307,7 @@ class SonosMediaPlayerEntity(SonosEntity, MediaPlayerEntity):
@soco_error()
def set_volume_level(self, volume: float) -> None:
"""Set volume level, range 0..1."""
self.soco.volume = int(round(volume * 100))
self.soco.volume = round(volume * 100)
@soco_error(UPNP_ERRORS_TO_IGNORE)
def set_shuffle(self, shuffle: bool) -> None:
@@ -176,7 +176,7 @@ class TelldusLiveSensor(TelldusLiveEntity, SensorEntity):
@property
def _value_as_humidity(self):
"""Return the value as humidity."""
return int(round(float(self._value)))
return round(float(self._value))
@property
def native_value(self):
@@ -88,7 +88,7 @@ class TwinklyCoordinator(DataUpdateCoordinator[TwinklyData]):
brightness = (
int(brightness["value"]) if brightness["mode"] == "enabled" else 100
)
brightness = int(round(brightness * 2.55)) if is_on else 0
brightness = round(brightness * 2.55) if is_on else 0
if self.device_name != device_info[DEV_NAME]:
self._async_update_device_info(device_info[DEV_NAME])
return TwinklyData(
@@ -362,7 +362,7 @@ class LgWebOSMediaPlayerEntity(RestoreEntity, MediaPlayerEntity):
@cmd
async def async_set_volume_level(self, volume: float) -> None:
"""Set volume level, range 0..1."""
tv_volume = int(round(volume * 100))
tv_volume = round(volume * 100)
await self._client.set_volume(tv_volume)
@cmd
+1 -1
View File
@@ -151,4 +151,4 @@ class ZerprocLight(LightEntity):
self._attr_is_on = state.is_on
hsv = color_util.color_RGB_to_hsv(*state.color)
self._attr_hs_color = hsv[:2]
self._attr_brightness = int(round((hsv[2] / 100) * 255))
self._attr_brightness = round((hsv[2] / 100) * 255)
+1 -1
View File
@@ -76,7 +76,7 @@ DATA_ENTITY_SOURCE = "entity_info"
# Used when converting float states to string: limit precision according to machine
# epsilon to make the string representation readable
FLOAT_PRECISION = abs(int(math.floor(math.log10(abs(sys.float_info.epsilon))))) - 1
FLOAT_PRECISION = abs(math.floor(math.log10(abs(sys.float_info.epsilon)))) - 1
# How many times per hour we allow capabilities to be updated before logging a warning
CAPABILITIES_UPDATE_LIMIT = 100
+2 -2
View File
@@ -170,13 +170,13 @@ def icon_for_battery_level(
if battery_level is None:
return f"{icon}-unknown"
if charging and battery_level > 10:
icon += f"-charging-{int(round(battery_level / 20 - 0.01)) * 20}"
icon += f"-charging-{round(battery_level / 20 - 0.01) * 20}"
elif charging:
icon += "-outline"
elif battery_level <= 5:
icon += "-alert"
elif 5 < battery_level < 95:
icon += f"-{int(round(battery_level / 10 - 0.01)) * 10}"
icon += f"-{round(battery_level / 10 - 0.01) * 10}"
return icon
+2 -2
View File
@@ -82,8 +82,8 @@ def async_setup(hass: HomeAssistant) -> bool:
@callback
def _async_adjust_lru_sizes(_: Any) -> None:
"""Adjust the lru cache sizes."""
new_size = int(
round(hass.states.async_entity_ids_count() * ENTITY_COUNT_GROWTH_FACTOR)
new_size = round(
hass.states.async_entity_ids_count() * ENTITY_COUNT_GROWTH_FACTOR
)
for lru in (CACHED_TEMPLATE_LRU, CACHED_TEMPLATE_NO_COLLECT_LRU):
# There is no typing for LRU
+1 -1
View File
@@ -408,7 +408,7 @@ def match_max_scale(
factor = 0.0
else:
factor = max_in / max_out
return tuple(int(round(i * factor)) for i in output_colors)
return tuple(round(i * factor) for i in output_colors)
def color_rgb_to_rgbw(r: int, g: int, b: int) -> tuple[int, int, int, int]:
+1
View File
@@ -736,6 +736,7 @@ select = [
"RUF032", # Decimal() called with float literal argument
"RUF033", # __post_init__ method with argument defaults
"RUF034", # Useless if-else condition
"RUF046", # Unnecessary cast to int
"RUF051", # Use dict.pop(key, None) instead of if-key-in-dict-del
"RUF059", # unused-unpacked-variable
"RUF100", # Unused `noqa` directive
@@ -162,8 +162,8 @@
# name: test_light_setup_with_device[light.some_device-state]
StateSnapshot({
'attributes': ReadOnlyDict({
'brightness': 1,
'color_mode': <ColorMode.BRIGHTNESS: 'brightness'>,
'brightness': None,
'color_mode': None,
'friendly_name': 'some device',
'supported_color_modes': list([
<ColorMode.BRIGHTNESS: 'brightness'>,
@@ -175,6 +175,6 @@
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'on',
'state': 'off',
})
# ---
+3
View File
@@ -27,6 +27,9 @@ async def test_light_setup_with_device(
"some_device": {},
}
pydeako_deako_mock.return_value.get_name.return_value = "some device"
pydeako_deako_mock.return_value.get_state.return_value = {
"power": False,
}
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
+8 -8
View File
@@ -58,11 +58,11 @@ async def test_lru_increases_with_many_entities(hass: HomeAssistant) -> None:
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=10))
await hass.async_block_till_done()
assert template_states.CACHED_TEMPLATE_LRU.get_size() == int(
round(mock_entity_count * template_states.ENTITY_COUNT_GROWTH_FACTOR)
assert template_states.CACHED_TEMPLATE_LRU.get_size() == round(
mock_entity_count * template_states.ENTITY_COUNT_GROWTH_FACTOR
)
assert template_states.CACHED_TEMPLATE_NO_COLLECT_LRU.get_size() == int(
round(mock_entity_count * template_states.ENTITY_COUNT_GROWTH_FACTOR)
assert template_states.CACHED_TEMPLATE_NO_COLLECT_LRU.get_size() == round(
mock_entity_count * template_states.ENTITY_COUNT_GROWTH_FACTOR
)
await hass.async_stop()
@@ -73,11 +73,11 @@ async def test_lru_increases_with_many_entities(hass: HomeAssistant) -> None:
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=20))
await hass.async_block_till_done()
assert template_states.CACHED_TEMPLATE_LRU.get_size() == int(
round(mock_entity_count * template_states.ENTITY_COUNT_GROWTH_FACTOR)
assert template_states.CACHED_TEMPLATE_LRU.get_size() == round(
mock_entity_count * template_states.ENTITY_COUNT_GROWTH_FACTOR
)
assert template_states.CACHED_TEMPLATE_NO_COLLECT_LRU.get_size() == int(
round(mock_entity_count * template_states.ENTITY_COUNT_GROWTH_FACTOR)
assert template_states.CACHED_TEMPLATE_NO_COLLECT_LRU.get_size() == round(
mock_entity_count * template_states.ENTITY_COUNT_GROWTH_FACTOR
)
+1 -1
View File
@@ -41,7 +41,7 @@ def test_battery_icon() -> None:
else:
postfix_charging = "-charging-100"
if 5 < level < 95:
postfix = f"-{int(round(level / 10 - 0.01)) * 10}"
postfix = f"-{round(level / 10 - 0.01) * 10}"
elif level <= 5:
postfix = "-alert"
else: