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.0 #135197

Draft
wants to merge 3 commits into
base: dev
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 2 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.0
hooks:
- id: ruff
args:
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/backup_restore.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ def _extract_backup(
Path(
tempdir,
"extracted",
f"homeassistant.tar{'.gz' if backup_meta["compressed"] else ''}",
f"homeassistant.tar{'.gz' if backup_meta['compressed'] else ''}",
),
gzip=backup_meta["compressed"],
key=password_to_key(restore_content.password)
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/advantage_air/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ class AdvantageAirZoneMotion(AdvantageAirZoneEntity, BinarySensorEntity):
def __init__(self, instance: AdvantageAirData, ac_key: str, zone_key: str) -> None:
"""Initialize an Advantage Air Zone Motion sensor."""
super().__init__(instance, ac_key, zone_key)
self._attr_name = f'{self._zone["name"]} motion'
self._attr_name = f"{self._zone['name']} motion"
self._attr_unique_id += "-motion"

@property
Expand All @@ -84,7 +84,7 @@ class AdvantageAirZoneMyZone(AdvantageAirZoneEntity, BinarySensorEntity):
def __init__(self, instance: AdvantageAirData, ac_key: str, zone_key: str) -> None:
"""Initialize an Advantage Air Zone MyZone sensor."""
super().__init__(instance, ac_key, zone_key)
self._attr_name = f'{self._zone["name"]} myZone'
self._attr_name = f"{self._zone['name']} myZone"
self._attr_unique_id += "-myzone"

@property
Expand Down
6 changes: 3 additions & 3 deletions homeassistant/components/advantage_air/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ class AdvantageAirZoneVent(AdvantageAirZoneEntity, SensorEntity):
def __init__(self, instance: AdvantageAirData, ac_key: str, zone_key: str) -> None:
"""Initialize an Advantage Air Zone Vent Sensor."""
super().__init__(instance, ac_key, zone_key=zone_key)
self._attr_name = f'{self._zone["name"]} vent'
self._attr_name = f"{self._zone['name']} vent"
self._attr_unique_id += "-vent"

@property
Expand Down Expand Up @@ -131,7 +131,7 @@ class AdvantageAirZoneSignal(AdvantageAirZoneEntity, SensorEntity):
def __init__(self, instance: AdvantageAirData, ac_key: str, zone_key: str) -> None:
"""Initialize an Advantage Air Zone wireless signal sensor."""
super().__init__(instance, ac_key, zone_key)
self._attr_name = f'{self._zone["name"]} signal'
self._attr_name = f"{self._zone['name']} signal"
self._attr_unique_id += "-signal"

@property
Expand Down Expand Up @@ -165,7 +165,7 @@ class AdvantageAirZoneTemp(AdvantageAirZoneEntity, SensorEntity):
def __init__(self, instance: AdvantageAirData, ac_key: str, zone_key: str) -> None:
"""Initialize an Advantage Air Zone Temp Sensor."""
super().__init__(instance, ac_key, zone_key)
self._attr_name = f'{self._zone["name"]} temperature'
self._attr_name = f"{self._zone['name']} temperature"
self._attr_unique_id += "-temp"

@property
Expand Down
3 changes: 1 addition & 2 deletions homeassistant/components/airthings/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,8 +155,7 @@ def __init__(
self._id = airthings_device.device_id
self._attr_device_info = DeviceInfo(
configuration_url=(
"https://dashboard.airthings.com/devices/"
f"{airthings_device.device_id}"
f"https://dashboard.airthings.com/devices/{airthings_device.device_id}"
),
identifiers={(DOMAIN, airthings_device.device_id)},
name=airthings_device.name,
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/airvisual_pro/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ class AirVisualProMeasurementDescription(SensorEntityDescription):
state_class=SensorStateClass.MEASUREMENT,
value_fn=lambda settings, status, measurements, history: int(
history.get(
f'Outdoor {"AQI(US)" if settings["is_aqi_usa"] else "AQI(CN)"}', -1
f"Outdoor {'AQI(US)' if settings['is_aqi_usa'] else 'AQI(CN)'}", -1
)
),
translation_key="outdoor_air_quality_index",
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 @@ -1463,9 +1463,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
4 changes: 2 additions & 2 deletions homeassistant/components/automation/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -636,9 +636,9 @@ async def async_trigger(
alias = ""
if "trigger" in run_variables:
if "description" in run_variables["trigger"]:
reason = f' by {run_variables["trigger"]["description"]}'
reason = f" by {run_variables['trigger']['description']}"
if "alias" in run_variables["trigger"]:
alias = f' trigger \'{run_variables["trigger"]["alias"]}\''
alias = f" trigger '{run_variables['trigger']['alias']}'"
self._logger.debug("Automation%s triggered%s", alias, reason)

# Create a new context referring to the old context.
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/backup/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -753,7 +753,7 @@ async def _async_create_backup(

backup_name = (
name
or f"{"Automatic" if with_automatic_settings else "Custom"} backup {HAVERSION}"
or f"{'Automatic' if with_automatic_settings else 'Custom'} backup {HAVERSION}"
)

try:
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/balboa/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def __init__(self, client: SpaClient, key: str) -> None:
"""Initialize the control."""
mac = client.mac_address
model = client.model
self._attr_unique_id = f'{model}-{key}-{mac.replace(":","")[-6:]}'
self._attr_unique_id = f"{model}-{key}-{mac.replace(':', '')[-6:]}"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, mac)},
name=model,
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/bayesian/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ class NumericConfig(NamedTuple):
for i, tup in enumerate(intervals):
if len(intervals) > i + 1 and tup.below > intervals[i + 1].above:
raise vol.Invalid(
f"Ranges for bayesian numeric state entities must not overlap, but {ent_id} has overlapping ranges, above:{tup.above}, below:{tup.below} overlaps with above:{intervals[i+1].above}, below:{intervals[i+1].below}."
f"Ranges for bayesian numeric state entities must not overlap, but {ent_id} has overlapping ranges, above:{tup.above}, below:{tup.below} overlaps with above:{intervals[i + 1].above}, below:{intervals[i + 1].below}."
)
return configs

Expand Down Expand Up @@ -206,7 +206,7 @@ async def async_setup_platform(
broken_observations: list[dict[str, Any]] = []
for observation in observations:
if CONF_P_GIVEN_F not in observation:
text: str = f"{name}/{observation.get(CONF_ENTITY_ID,'')}{observation.get(CONF_VALUE_TEMPLATE,'')}"
text: str = f"{name}/{observation.get(CONF_ENTITY_ID, '')}{observation.get(CONF_VALUE_TEMPLATE, '')}"
raise_no_prob_given_false(hass, text)
_LOGGER.error("Missing prob_given_false YAML entry for %s", text)
broken_observations.append(observation)
Expand Down
5 changes: 2 additions & 3 deletions homeassistant/components/blueprint/importer.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ def _extract_blueprint_from_community_topic(
)

return ImportedBlueprint(
f'{post["username"]}/{topic["slug"]}', block_content, blueprint
f"{post['username']}/{topic['slug']}", block_content, blueprint
)


Expand Down Expand Up @@ -173,8 +173,7 @@ async def fetch_blueprint_from_github_url(

parsed_import_url = yarl.URL(import_url)
suggested_filename = f"{parsed_import_url.parts[1]}/{parsed_import_url.parts[-1]}"
if suggested_filename.endswith(".yaml"):
suggested_filename = suggested_filename[:-5]
suggested_filename = suggested_filename.removesuffix(".yaml")

return ImportedBlueprint(suggested_filename, raw_yaml, blueprint)

Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/bthome/logbook.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def async_describe_bthome_event(event: Event[BTHomeBleEvent]) -> dict[str, str]:
"""Describe bthome logbook event."""
data = event.data
device = dev_reg.async_get(data["device_id"])
name = device and device.name or f'BTHome {data["address"]}'
name = device and device.name or f"BTHome {data['address']}"
if properties := data["event_properties"]:
message = f"{data['event_class']} {data['event_type']}: {properties}"
else:
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/compensation/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def datapoints_greater_than_degree(value: dict) -> dict:
if len(value[CONF_DATAPOINTS]) <= value[CONF_DEGREE]:
raise vol.Invalid(
f"{CONF_DATAPOINTS} must have at least"
f" {value[CONF_DEGREE]+1} {CONF_DATAPOINTS}"
f" {value[CONF_DEGREE] + 1} {CONF_DATAPOINTS}"
)

return value
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
2 changes: 1 addition & 1 deletion homeassistant/components/doods/image_processing.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,7 @@ def _save_image(self, image, matches, paths):

# Draw detected objects
for instance in values:
box_label = f'{label} {instance["score"]:.1f}%'
box_label = f"{label} {instance['score']:.1f}%"
# Already scaled, use 1 for width and height
draw_box(
draw,
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/duke_energy/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ async def _async_update_data(self) -> None:
)
continue

id_prefix = f"{meter["serviceType"].lower()}_{serial_number}"
id_prefix = f"{meter['serviceType'].lower()}_{serial_number}"
consumption_statistic_id = f"{DOMAIN}:{id_prefix}_energy_consumption"
self._statistic_ids.add(consumption_statistic_id)
_LOGGER.debug(
Expand Down Expand Up @@ -136,7 +136,7 @@ async def _async_update_data(self) -> None:
)

name_prefix = (
f"Duke Energy " f"{meter["serviceType"].capitalize()} {serial_number}"
f"Duke Energy {meter['serviceType'].capitalize()} {serial_number}"
)
consumption_metadata = StatisticMetaData(
has_mean=False,
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/ecobee/climate.py
Original file line number Diff line number Diff line change
Expand Up @@ -603,7 +603,7 @@ def remote_sensor_devices(self) -> list:
"""Return the remote sensor device name_by_user or name for the thermostat."""
return sorted(
[
f'{item["name_by_user"]} ({item["id"]})'
f"{item['name_by_user']} ({item['id']})"
for item in self.remote_sensor_ids_names
]
)
Expand Down Expand Up @@ -873,7 +873,7 @@ def set_sensors_used_in_climate(
translation_placeholders={
"options": ", ".join(
[
f'{item["name_by_user"]} ({item["id"]})'
f"{item['name_by_user']} ({item['id']})"
for item in self.remote_sensor_ids_names
]
)
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/ecobee/notify.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def __init__(self, data: EcobeeData, thermostat_index: int) -> None:
"""Initialize the thermostat."""
super().__init__(data, thermostat_index)
self._attr_unique_id = (
f"{self.thermostat["identifier"]}_notify_{thermostat_index}"
f"{self.thermostat['identifier']}_notify_{thermostat_index}"
)

def send_message(self, message: str, title: str | None = None) -> None:
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/flux_led/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ def _async_migrator(entity_entry: er.RegistryEntry) -> dict[str, Any] | None:
and mac_matches_by_one(entity_mac, unique_id)
):
# Old format {dhcp_mac}....., New format {discovery_mac}....
new_unique_id = f"{unique_id}{entity_unique_id[len(unique_id):]}"
new_unique_id = f"{unique_id}{entity_unique_id[len(unique_id) :]}"
else:
return None
_LOGGER.debug(
Expand Down
3 changes: 1 addition & 2 deletions homeassistant/components/fritz/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,8 +166,7 @@ async def async_step_ssdp(

uuid: str | None
if uuid := discovery_info.upnp.get(ssdp.ATTR_UPNP_UDN):
if uuid.startswith("uuid:"):
uuid = uuid[5:]
uuid = uuid.removeprefix("uuid:")
await self.async_set_unique_id(uuid)
self._abort_if_unique_id_configured({CONF_HOST: self._host})

Expand Down
3 changes: 1 addition & 2 deletions homeassistant/components/fritzbox/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,7 @@ async def async_step_ssdp(
return self.async_abort(reason="ignore_ip6_link_local")

if uuid := discovery_info.upnp.get(ssdp.ATTR_UPNP_UDN):
if uuid.startswith("uuid:"):
uuid = uuid[5:]
uuid = uuid.removeprefix("uuid:")
await self.async_set_unique_id(uuid)
self._abort_if_unique_id_configured({CONF_HOST: host})

Expand Down
8 changes: 4 additions & 4 deletions homeassistant/components/fronius/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -794,7 +794,7 @@ def __init__(
"unit"
)
self._attr_unique_id = (
f'{logger_data["unique_identifier"]["value"]}-{description.key}'
f"{logger_data['unique_identifier']['value']}-{description.key}"
)


Expand All @@ -815,7 +815,7 @@ def __init__(
if (meter_uid := meter_data["serial"]["value"]) == "n.a.":
meter_uid = (
f"{coordinator.solar_net.solar_net_device_id}:"
f'{meter_data["model"]["value"]}'
f"{meter_data['model']['value']}"
)

self._attr_device_info = DeviceInfo(
Expand Down Expand Up @@ -849,7 +849,7 @@ def __init__(
sw_version=device_data["software"]["value"],
via_device=(DOMAIN, coordinator.solar_net.solar_net_device_id),
)
self._attr_unique_id = f'{device_data["serial"]["value"]}-{description.key}'
self._attr_unique_id = f"{device_data['serial']['value']}-{description.key}"


class PowerFlowSensor(_FroniusSensorEntity):
Expand Down Expand Up @@ -883,7 +883,7 @@ def __init__(
super().__init__(coordinator, description, solar_net_id)
storage_data = self._device_data()

self._attr_unique_id = f'{storage_data["serial"]["value"]}-{description.key}'
self._attr_unique_id = f"{storage_data['serial']['value']}-{description.key}"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, storage_data["serial"]["value"])},
manufacturer=storage_data["manufacturer"]["value"],
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/frontier_silicon/browse_media.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def _item_preset_payload(preset: Preset, player_mode: str) -> BrowseMedia:
media_content_type=MediaType.CHANNEL,
# We add 1 to the preset key to keep it in sync with the numbering shown
# on the interface of the device
media_content_id=f"{player_mode}/{MEDIA_CONTENT_ID_PRESET}/{int(preset.key)+1}",
media_content_id=f"{player_mode}/{MEDIA_CONTENT_ID_PRESET}/{int(preset.key) + 1}",
can_play=True,
can_expand=False,
)
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
3 changes: 1 addition & 2 deletions homeassistant/components/harmony/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,7 @@ async def connect(self) -> None:
except (ValueError, AttributeError) as err:
await self._client.close()
raise ConfigEntryNotReady(
f"{self.name}: Error {err} while connected HUB at:"
f" {self._address}:8088"
f"{self.name}: Error {err} while connected HUB at: {self._address}:8088"
) from err
if not connected:
await self._client.close()
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/hisense_aehw4a1/climate.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ async def async_update(self) -> None:
fan_mode = status["wind_status"]
self._attr_fan_mode = AC_TO_HA_FAN_MODES[fan_mode]

swing_mode = f'{status["up_down"]}{status["left_right"]}'
swing_mode = f"{status['up_down']}{status['left_right']}"
self._attr_swing_mode = AC_TO_HA_SWING[swing_mode]

if self._attr_hvac_mode in (HVACMode.COOL, HVACMode.HEAT):
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/hive/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def __init__(self, hive: Hive, hive_device: dict[str, Any]) -> None:
self.hive = hive
self.device = hive_device
self._attr_name = self.device["haName"]
self._attr_unique_id = f'{self.device["hiveID"]}-{self.device["hiveType"]}'
self._attr_unique_id = f"{self.device['hiveID']}-{self.device['hiveType']}"
self._attr_device_info = DeviceInfo(
identifiers={(DOMAIN, self.device["device_id"])},
model=self.device["deviceData"]["model"],
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/homekit/iidmanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,8 +102,8 @@ def get_or_allocate_iid(
char_hap_type: str | None = uuid_to_hap_type(char_uuid) if char_uuid else None
# Allocation key must be a string since we are saving it to JSON
allocation_key = (
f'{service_hap_type}_{service_unique_id or ""}_'
f'{char_hap_type or ""}_{char_unique_id or ""}'
f"{service_hap_type}_{service_unique_id or ''}_"
f"{char_hap_type or ''}_{char_unique_id or ''}"
)
# AID must be a string since JSON keys cannot be int
aid_str = str(aid)
Expand Down
Loading
Loading