Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bump ruff to 0.9.1 #135197

Merged
merged 8 commits into from
Jan 14, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.8.6
rev: v0.9.1
hooks:
- id: ruff
args:
Expand Down
6 changes: 3 additions & 3 deletions homeassistant/components/assist_pipeline/pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -1472,9 +1472,9 @@ async def execute(self) -> None:
if stt_audio_buffer:
# Send audio in the buffer first to speech-to-text, then move on to stt_stream.
# This is basically an async itertools.chain.
async def buffer_then_audio_stream() -> (
AsyncGenerator[EnhancedAudioChunk]
):
async def buffer_then_audio_stream() -> AsyncGenerator[
EnhancedAudioChunk
]:
# Buffered audio
for chunk in stt_audio_buffer:
yield chunk
Expand Down
18 changes: 9 additions & 9 deletions homeassistant/components/device_tracker/legacy.py
Original file line number Diff line number Diff line change
Expand Up @@ -978,9 +978,9 @@ def scan_devices(self) -> list[str]:

async def async_scan_devices(self) -> list[str]:
"""Scan for devices."""
assert (
self.hass is not None
), "hass should be set by async_setup_scanner_platform"
assert self.hass is not None, (
"hass should be set by async_setup_scanner_platform"
)
return await self.hass.async_add_executor_job(self.scan_devices)

def get_device_name(self, device: str) -> str | None:
Expand All @@ -989,9 +989,9 @@ def get_device_name(self, device: str) -> str | None:

async def async_get_device_name(self, device: str) -> str | None:
"""Get the name of a device."""
assert (
self.hass is not None
), "hass should be set by async_setup_scanner_platform"
assert self.hass is not None, (
"hass should be set by async_setup_scanner_platform"
)
return await self.hass.async_add_executor_job(self.get_device_name, device)

def get_extra_attributes(self, device: str) -> dict:
Expand All @@ -1000,9 +1000,9 @@ def get_extra_attributes(self, device: str) -> dict:

async def async_get_extra_attributes(self, device: str) -> dict:
"""Get the extra attributes of a device."""
assert (
self.hass is not None
), "hass should be set by async_setup_scanner_platform"
assert self.hass is not None, (
"hass should be set by async_setup_scanner_platform"
)
return await self.hass.async_add_executor_job(self.get_extra_attributes, device)


Expand Down
6 changes: 3 additions & 3 deletions homeassistant/components/google_cloud/stt.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,9 @@ async def async_process_audio_stream(
)
)

async def request_generator() -> (
AsyncGenerator[speech_v1.StreamingRecognizeRequest]
):
async def request_generator() -> AsyncGenerator[
speech_v1.StreamingRecognizeRequest
]:
# The first request must only contain a streaming_config
yield speech_v1.StreamingRecognizeRequest(streaming_config=streaming_config)
# All subsequent requests must only contain audio_content
Expand Down
6 changes: 3 additions & 3 deletions homeassistant/components/logbook/processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,9 +115,9 @@ def __init__(
include_entity_name: bool = True,
) -> None:
"""Init the event stream."""
assert not (
context_id and (entity_ids or device_ids)
), "can't pass in both context_id and (entity_ids or device_ids)"
assert not (context_id and (entity_ids or device_ids)), (
"can't pass in both context_id and (entity_ids or device_ids)"
)
self.hass = hass
self.ent_reg = er.async_get(hass)
self.event_types = event_types
Expand Down
6 changes: 2 additions & 4 deletions homeassistant/components/matter/climate.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,13 +310,11 @@ def _update_from_device(self) -> None:
):
match running_state_value:
case (
ThermostatRunningState.Heat
| ThermostatRunningState.HeatStage2
ThermostatRunningState.Heat | ThermostatRunningState.HeatStage2
):
self._attr_hvac_action = HVACAction.HEATING
case (
ThermostatRunningState.Cool
| ThermostatRunningState.CoolStage2
ThermostatRunningState.Cool | ThermostatRunningState.CoolStage2
):
self._attr_hvac_action = HVACAction.COOLING
case (
Expand Down
6 changes: 3 additions & 3 deletions homeassistant/components/modbus/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,9 @@ def __init__(
def get_optional_numeric_config(config_name: str) -> int | float | None:
if (val := entry.get(config_name)) is None:
return None
assert isinstance(
val, (float, int)
), f"Expected float or int but {config_name} was {type(val)}"
assert isinstance(val, (float, int)), (
f"Expected float or int but {config_name} was {type(val)}"
)
return val

self._min_value = get_optional_numeric_config(CONF_MIN_VALUE)
Expand Down
10 changes: 5 additions & 5 deletions homeassistant/components/nmbs/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ async def async_step_user(
)
self._abort_if_unique_id_configured()

config_entry_name = f"Train from {station_from["standardname"]} to {station_to["standardname"]}"
config_entry_name = f"Train from {station_from['standardname']} to {station_to['standardname']}"
return self.async_create_entry(
title=config_entry_name,
data=user_input,
Expand Down Expand Up @@ -157,18 +157,18 @@ async def async_step_import(self, user_input: dict[str, Any]) -> ConfigFlowResul
if entity_id := entity_registry.async_get_entity_id(
Platform.SENSOR,
DOMAIN,
f"{prefix}_{station_live["standardname"]}_{station_from["standardname"]}_{station_to["standardname"]}",
f"{prefix}_{station_live['standardname']}_{station_from['standardname']}_{station_to['standardname']}",
):
new_unique_id = f"{DOMAIN}_{prefix}_{station_live["id"]}_{station_from["id"]}_{station_to["id"]}"
new_unique_id = f"{DOMAIN}_{prefix}_{station_live['id']}_{station_from['id']}_{station_to['id']}"
entity_registry.async_update_entity(
entity_id, new_unique_id=new_unique_id
)
if entity_id := entity_registry.async_get_entity_id(
Platform.SENSOR,
DOMAIN,
f"{prefix}_{station_live["name"]}_{station_from["name"]}_{station_to["name"]}",
f"{prefix}_{station_live['name']}_{station_from['name']}_{station_to['name']}",
):
new_unique_id = f"{DOMAIN}_{prefix}_{station_live["id"]}_{station_from["id"]}_{station_to["id"]}"
new_unique_id = f"{DOMAIN}_{prefix}_{station_live['id']}_{station_from['id']}_{station_to['id']}"
entity_registry.async_update_entity(
entity_id, new_unique_id=new_unique_id
)
Expand Down
9 changes: 4 additions & 5 deletions homeassistant/components/nmbs/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,15 +201,14 @@ def __init__(
@property
def name(self) -> str:
"""Return the sensor default name."""
return f"Trains in {self._station["standardname"]}"
return f"Trains in {self._station['standardname']}"

@property
def unique_id(self) -> str:
"""Return the unique ID."""

unique_id = (
f"{self._station["id"]}_{self._station_from["id"]}_"
f"{self._station_to["id"]}"
f"{self._station['id']}_{self._station_from['id']}_{self._station_to['id']}"
)
return f"nmbs_live_{unique_id}"

Expand Down Expand Up @@ -302,15 +301,15 @@ def __init__(
@property
def unique_id(self) -> str:
"""Return the unique ID."""
unique_id = f"{self._station_from["id"]}_{self._station_to["id"]}"
unique_id = f"{self._station_from['id']}_{self._station_to['id']}"

return f"nmbs_connection_{unique_id}"

@property
def name(self) -> str:
"""Return the name of the sensor."""
if self._name is None:
return f"Train from {self._station_from["standardname"]} to {self._station_to["standardname"]}"
return f"Train from {self._station_from['standardname']} to {self._station_to['standardname']}"
return self._name

@property
Expand Down
12 changes: 6 additions & 6 deletions homeassistant/components/onvif/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,9 +252,9 @@ def __init__(self, event_manager: EventManager) -> None:

async def async_start(self) -> bool:
"""Start pullpoint subscription."""
assert (
self.state == PullPointManagerState.STOPPED
), "PullPoint manager already started"
assert self.state == PullPointManagerState.STOPPED, (
"PullPoint manager already started"
)
LOGGER.debug("%s: Starting PullPoint manager", self._name)
if not await self._async_start_pullpoint():
self.state = PullPointManagerState.FAILED
Expand Down Expand Up @@ -501,9 +501,9 @@ def __init__(self, event_manager: EventManager) -> None:
async def async_start(self) -> bool:
"""Start polling events."""
LOGGER.debug("%s: Starting webhook manager", self._name)
assert (
self.state == WebHookManagerState.STOPPED
), "Webhook manager already started"
assert self.state == WebHookManagerState.STOPPED, (
"Webhook manager already started"
)
assert self._webhook_url is None, "Webhook already registered"
self._async_register_webhook()
if not await self._async_start_webhook():
Expand Down
8 changes: 3 additions & 5 deletions homeassistant/components/openhome/media_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,9 @@ async def async_setup_entry(
]


def catch_request_errors[_OpenhomeDeviceT: OpenhomeDevice, **_P, _R]() -> (
Callable[
[_FuncType[_OpenhomeDeviceT, _P, _R]], _ReturnFuncType[_OpenhomeDeviceT, _P, _R]
]
):
def catch_request_errors[_OpenhomeDeviceT: OpenhomeDevice, **_P, _R]() -> Callable[
[_FuncType[_OpenhomeDeviceT, _P, _R]], _ReturnFuncType[_OpenhomeDeviceT, _P, _R]
]:
"""Catch TimeoutError, aiohttp.ClientError, UpnpError errors."""

def call_wrapper(
Expand Down
6 changes: 3 additions & 3 deletions homeassistant/components/qwikswitch/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,9 @@ def __init__(self, sensor):

self._decode, self.unit = SENSORS[sensor_type]
# this cannot happen because it only happens in bool and this should be redirected to binary_sensor
assert not isinstance(
self.unit, type
), f"boolean sensor id={sensor['id']} name={sensor['name']}"
assert not isinstance(self.unit, type), (
f"boolean sensor id={sensor['id']} name={sensor['name']}"
)

@callback
def update_packet(self, packet):
Expand Down
12 changes: 6 additions & 6 deletions homeassistant/components/recorder/migration.py
Original file line number Diff line number Diff line change
Expand Up @@ -2752,9 +2752,9 @@ def migrate_data_impl(self, instance: Recorder) -> DataMigrationStatus:
for db_event_type in missing_db_event_types:
# We cannot add the assigned ids to the event_type_manager
# because the commit could get rolled back
assert (
db_event_type.event_type is not None
), "event_type should never be None"
assert db_event_type.event_type is not None, (
"event_type should never be None"
)
event_type_to_id[db_event_type.event_type] = (
db_event_type.event_type_id
)
Expand Down Expand Up @@ -2830,9 +2830,9 @@ def migrate_data_impl(self, instance: Recorder) -> DataMigrationStatus:
for db_states_metadata in missing_states_metadata:
# We cannot add the assigned ids to the event_type_manager
# because the commit could get rolled back
assert (
db_states_metadata.entity_id is not None
), "entity_id should never be None"
assert db_states_metadata.entity_id is not None, (
"entity_id should never be None"
)
entity_id_to_metadata_id[db_states_metadata.entity_id] = (
db_states_metadata.metadata_id
)
Expand Down
6 changes: 3 additions & 3 deletions homeassistant/components/recorder/pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,9 @@ def __init__( # pylint: disable=super-init-not-called
) -> None:
"""Create the pool."""
kw["pool_size"] = POOL_SIZE
assert (
recorder_and_worker_thread_ids is not None
), "recorder_and_worker_thread_ids is required"
assert recorder_and_worker_thread_ids is not None, (
"recorder_and_worker_thread_ids is required"
)
self.recorder_and_worker_thread_ids = recorder_and_worker_thread_ids
SingletonThreadPool.__init__(self, creator, **kw)

Expand Down
30 changes: 12 additions & 18 deletions homeassistant/components/recorder/statistics.py
Original file line number Diff line number Diff line change
Expand Up @@ -968,12 +968,10 @@ def _reduce_statistics(
return result


def reduce_day_ts_factory() -> (
tuple[
Callable[[float, float], bool],
Callable[[float], tuple[float, float]],
]
):
def reduce_day_ts_factory() -> tuple[
Callable[[float, float], bool],
Callable[[float], tuple[float, float]],
]:
"""Return functions to match same day and day start end."""
_lower_bound: float = 0
_upper_bound: float = 0
Expand Down Expand Up @@ -1017,12 +1015,10 @@ def _reduce_statistics_per_day(
)


def reduce_week_ts_factory() -> (
tuple[
Callable[[float, float], bool],
Callable[[float], tuple[float, float]],
]
):
def reduce_week_ts_factory() -> tuple[
Callable[[float, float], bool],
Callable[[float], tuple[float, float]],
]:
"""Return functions to match same week and week start end."""
_lower_bound: float = 0
_upper_bound: float = 0
Expand Down Expand Up @@ -1075,12 +1071,10 @@ def _find_month_end_time(timestamp: datetime) -> datetime:
)


def reduce_month_ts_factory() -> (
tuple[
Callable[[float, float], bool],
Callable[[float], tuple[float, float]],
]
):
def reduce_month_ts_factory() -> tuple[
Callable[[float, float], bool],
Callable[[float], tuple[float, float]],
]:
"""Return functions to match same month and month start end."""
_lower_bound: float = 0
_upper_bound: float = 0
Expand Down
6 changes: 3 additions & 3 deletions homeassistant/components/zeroconf/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -615,9 +615,9 @@ def info_from_service(service: AsyncServiceInfo) -> ZeroconfServiceInfo | None:
return None

if TYPE_CHECKING:
assert (
service.server is not None
), "server cannot be none if there are addresses"
assert service.server is not None, (
"server cannot be none if there are addresses"
)
return ZeroconfServiceInfo(
ip_address=ip_address,
ip_addresses=ip_addresses,
Expand Down
6 changes: 3 additions & 3 deletions homeassistant/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@
_function_cache: dict[str, Callable[[str, str, dict[str, str] | None], str]] = {}


def import_async_get_exception_message() -> (
Callable[[str, str, dict[str, str] | None], str]
):
def import_async_get_exception_message() -> Callable[
[str, str, dict[str, str] | None], str
]:
"""Return a method that can fetch a translated exception message.

Defaults to English, requires translations to already be cached.
Expand Down
6 changes: 3 additions & 3 deletions homeassistant/helpers/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -1480,9 +1480,9 @@ async def async_internal_added_to_hass(self) -> None:

if self.registry_entry is not None:
# This is an assert as it should never happen, but helps in tests
assert (
not self.registry_entry.disabled_by
), f"Entity '{self.entity_id}' is being added while it's disabled"
assert not self.registry_entry.disabled_by, (
f"Entity '{self.entity_id}' is being added while it's disabled"
)

self.async_on_remove(
async_track_entity_registry_updated_event(
Expand Down
6 changes: 3 additions & 3 deletions homeassistant/helpers/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,9 @@ def request_handler_factory(
) -> Callable[[web.Request], Awaitable[web.StreamResponse]]:
"""Wrap the handler classes."""
is_coroutinefunction = asyncio.iscoroutinefunction(handler)
assert is_coroutinefunction or is_callback(
handler
), "Handler should be a coroutine or a callback."
assert is_coroutinefunction or is_callback(handler), (
"Handler should be a coroutine or a callback."
)

async def handle(request: web.Request) -> web.StreamResponse:
"""Handle incoming request."""
Expand Down
Loading