Skip to content

Commit 1e5f5f4

Browse files
authored
Enable pylint consider-math-not-float check (home-assistant#154338)
1 parent 82c536a commit 1e5f5f4

File tree

11 files changed

+31
-22
lines changed

11 files changed

+31
-22
lines changed

homeassistant/components/habitica/todo.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
from enum import StrEnum
66
import logging
7+
import math
78
from typing import TYPE_CHECKING
89
from uuid import UUID
910

@@ -281,7 +282,7 @@ def todo_items(self) -> list[TodoItem]:
281282
return sorted(
282283
tasks,
283284
key=lambda task: (
284-
float("inf")
285+
math.inf
285286
if (uid := UUID(task.uid))
286287
not in (tasks_order := self.coordinator.data.user.tasksOrder.todos)
287288
else tasks_order.index(uid)
@@ -367,7 +368,7 @@ def todo_items(self) -> list[TodoItem]:
367368
return sorted(
368369
tasks,
369370
key=lambda task: (
370-
float("inf")
371+
math.inf
371372
if (uid := UUID(task.uid))
372373
not in (tasks_order := self.coordinator.data.user.tasksOrder.dailys)
373374
else tasks_order.index(uid)

homeassistant/components/knx/schema.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
from abc import ABC
66
from collections import OrderedDict
7+
import math
78
from typing import ClassVar, Final
89

910
import voluptuous as vol
@@ -86,15 +87,15 @@ def number_limit_sub_validator(entity_config: OrderedDict) -> OrderedDict:
8687
raise vol.Invalid(f"'type: {value_type}' is not a valid numeric sensor type.")
8788
# Infinity is not supported by Home Assistant frontend so user defined
8889
# config is required if if xknx DPTNumeric subclass defines it as limit.
89-
if min_config is None and dpt_class.value_min == float("-inf"):
90+
if min_config is None and dpt_class.value_min == -math.inf:
9091
raise vol.Invalid(f"'min' key required for value type '{value_type}'")
9192
if min_config is not None and min_config < dpt_class.value_min:
9293
raise vol.Invalid(
9394
f"'min: {min_config}' undercuts possible minimum"
9495
f" of value type '{value_type}': {dpt_class.value_min}"
9596
)
9697

97-
if max_config is None and dpt_class.value_max == float("inf"):
98+
if max_config is None and dpt_class.value_max == math.inf:
9899
raise vol.Invalid(f"'max' key required for value type '{value_type}'")
99100
if max_config is not None and max_config > dpt_class.value_max:
100101
raise vol.Invalid(

homeassistant/components/stream/recorder.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from collections import deque
66
from io import DEFAULT_BUFFER_SIZE, BytesIO
77
import logging
8+
import math
89
import os
910
from typing import TYPE_CHECKING
1011

@@ -76,7 +77,7 @@ async def async_record(self) -> None:
7677
# units which seem to be defined inversely to how stream time_bases are defined
7778
running_duration = 0
7879

79-
last_sequence = float("-inf")
80+
last_sequence = -math.inf
8081

8182
def write_segment(segment: Segment) -> None:
8283
"""Write a segment to output."""

homeassistant/components/stream/worker.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import datetime
1010
from io import SEEK_END, BytesIO
1111
import logging
12+
import math
1213
from threading import Event
1314
from typing import Any, Self, cast
1415

@@ -46,7 +47,7 @@
4647
from .hls import HlsStreamOutput
4748

4849
_LOGGER = logging.getLogger(__name__)
49-
NEGATIVE_INF = float("-inf")
50+
NEGATIVE_INF = -math.inf
5051

5152

5253
def redact_av_error_string(err: av.FFmpegError) -> str:

homeassistant/helpers/significant_change.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ async def async_check_significant_change(
3030
from __future__ import annotations
3131

3232
from collections.abc import Callable, Mapping
33+
import math
3334
from types import MappingProxyType
3435
from typing import Any, Protocol
3536

@@ -161,7 +162,7 @@ def percentage_change(old_state: float, new_state: float) -> float:
161162
try:
162163
return (abs(new_state - old_state) / old_state) * 100.0
163164
except ZeroDivisionError:
164-
return float("inf")
165+
return math.inf
165166

166167
return _check_numeric_change(old_state, new_state, change, percentage_change)
167168

pyproject.toml

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,6 @@ class-const-naming-style = "any"
161161
# possibly-used-before-assignment - too many errors / not necessarily issues
162162
# ---
163163
# Pylint CodeStyle plugin
164-
# consider-math-not-float
165164
# consider-using-namedtuple-or-dataclass - too opinionated
166165
# consider-using-assignment-expr - decision to use := better left to devs
167166
disable = [
@@ -182,7 +181,6 @@ disable = [
182181
"too-many-boolean-expressions",
183182
"too-many-positional-arguments",
184183
"wrong-import-order",
185-
"consider-math-not-float",
186184
"consider-using-namedtuple-or-dataclass",
187185
"consider-using-assignment-expr",
188186
"possibly-used-before-assignment",

tests/components/http/test_view.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from decimal import Decimal
44
from http import HTTPStatus
55
import json
6+
import math
67
from unittest.mock import AsyncMock, Mock
78

89
from aiohttp.web_exceptions import (
@@ -46,7 +47,7 @@ async def test_invalid_json(caplog: pytest.LogCaptureFixture) -> None:
4647

4748
async def test_nan_serialized_to_null() -> None:
4849
"""Test nan serialized to null JSON."""
49-
response = HomeAssistantView.json(float("NaN"))
50+
response = HomeAssistantView.json(math.nan)
5051
assert json.loads(response.body.decode("utf-8")) is None
5152

5253

tests/components/modbus/test_sensor.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
"""The tests for the Modbus sensor component."""
22

3+
import math
34
import struct
45

56
import pytest
@@ -738,8 +739,8 @@ async def test_all_sensor(hass: HomeAssistant, mock_do_cycle, expected) -> None:
738739
[
739740
0x5102,
740741
0x0304,
741-
int.from_bytes(struct.pack(">f", float("nan"))[0:2]),
742-
int.from_bytes(struct.pack(">f", float("nan"))[2:4]),
742+
int.from_bytes(struct.pack(">f", math.nan)[0:2]),
743+
int.from_bytes(struct.pack(">f", math.nan)[2:4]),
743744
],
744745
False,
745746
["34899771392.0", STATE_UNKNOWN],
@@ -753,8 +754,8 @@ async def test_all_sensor(hass: HomeAssistant, mock_do_cycle, expected) -> None:
753754
[
754755
0x5102,
755756
0x0304,
756-
int.from_bytes(struct.pack(">f", float("nan"))[0:2]),
757-
int.from_bytes(struct.pack(">f", float("nan"))[2:4]),
757+
int.from_bytes(struct.pack(">f", math.nan)[0:2]),
758+
int.from_bytes(struct.pack(">f", math.nan)[2:4]),
758759
],
759760
False,
760761
["34899771392.0", STATE_UNKNOWN],
@@ -1160,8 +1161,8 @@ async def test_wrong_unpack(hass: HomeAssistant, mock_do_cycle) -> None:
11601161
CONF_DATA_TYPE: DataType.FLOAT32,
11611162
},
11621163
[
1163-
int.from_bytes(struct.pack(">f", float("nan"))[0:2]),
1164-
int.from_bytes(struct.pack(">f", float("nan"))[2:4]),
1164+
int.from_bytes(struct.pack(">f", math.nan)[0:2]),
1165+
int.from_bytes(struct.pack(">f", math.nan)[2:4]),
11651166
],
11661167
STATE_UNKNOWN,
11671168
),
@@ -1224,8 +1225,8 @@ async def test_unpack_ok(hass: HomeAssistant, mock_do_cycle, expected) -> None:
12241225
# floats: nan, 10.600000381469727,
12251226
# 1.000879611487865e-28, 10.566553115844727
12261227
[
1227-
int.from_bytes(struct.pack(">f", float("nan"))[0:2]),
1228-
int.from_bytes(struct.pack(">f", float("nan"))[2:4]),
1228+
int.from_bytes(struct.pack(">f", math.nan)[0:2]),
1229+
int.from_bytes(struct.pack(">f", math.nan)[2:4]),
12291230
0x4129,
12301231
0x999A,
12311232
0x10FD,

tests/components/sensor/test_init.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from collections.abc import Generator
66
from datetime import UTC, date, datetime
77
from decimal import Decimal
8+
import math
89
from typing import Any
910
from unittest.mock import patch
1011

@@ -2313,9 +2314,11 @@ async def test_state_classes_with_invalid_unit_of_measurement(
23132314
(datetime(2012, 11, 10, 7, 35, 1), "non-numeric"),
23142315
(date(2012, 11, 10), "non-numeric"),
23152316
("inf", "non-finite"),
2316-
(float("inf"), "non-finite"),
2317+
(math.inf, "non-finite"),
2318+
(float("inf"), "non-finite"), # pylint: disable=consider-math-not-float
23172319
("nan", "non-finite"),
2318-
(float("nan"), "non-finite"),
2320+
(math.nan, "non-finite"),
2321+
(float("nan"), "non-finite"), # pylint: disable=consider-math-not-float
23192322
],
23202323
)
23212324
async def test_non_numeric_validation_error(

tests/components/websocket_api/test_commands.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from copy import deepcopy
55
import io
66
import logging
7+
import math
78
from typing import Any
89
from unittest.mock import ANY, AsyncMock, Mock, patch
910

@@ -1061,7 +1062,7 @@ async def test_get_states_not_allows_nan(
10611062
) -> None:
10621063
"""Test get_states command converts NaN to None."""
10631064
hass.states.async_set("greeting.hello", "world")
1064-
hass.states.async_set("greeting.bad", "data", {"hello": float("NaN")})
1065+
hass.states.async_set("greeting.bad", "data", {"hello": math.nan})
10651066
hass.states.async_set("greeting.bye", "universe")
10661067

10671068
await websocket_client.send_json_auto_id({"type": "get_states"})

0 commit comments

Comments
 (0)