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.0.254 #89273

Merged
merged 5 commits into from
Mar 7, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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/charliermarsh/ruff-pre-commit
rev: v0.0.253
rev: v0.0.254
hooks:
- id: ruff
args:
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/asuswrt/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,6 @@ def native_value(self) -> float | int | str | None:
"""Return current state."""
descr = self.entity_description
state: float | int | str | None = self.coordinator.data.get(descr.key)
if state is not None and descr.factor and isinstance(state, (float, int)):
if state is not None and descr.factor and isinstance(state, float | int):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Side note: The union syntax is 100 - 50 % slower on Python 3.10 and Python 3.11 than the tuple syntax, according to the issue for this feature in ruff.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For reference, this is the issue mentionned above: astral-sh/ruff#2923
See also PEP 604

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Side note: The union syntax is 100 - 50 % slower on Python 3.10 and Python 3.11 than the tuple syntax, according to the issue for this feature in ruff.

Does it make sense then to replace it if it's slower? The way I understand PEP 604, it's a new option to use the Union syntax. However the old way won't go anywhere anytime soon.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can add UP038 to ignore list, and I can revert commit 65a884a if that is what we want.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm all in favor of modern syntaxes, but we don't have to pay the performance price right now, which affects 95% of the userbase. I think we can reconsider once we run Python 3.11 on our main distribution.

For now, I rather have this one on the ignore list.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

return state / descr.factor
return state
2 changes: 1 addition & 1 deletion homeassistant/components/august/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ async def _async_initial_sync(self):
return_exceptions=True,
):
if isinstance(result, Exception) and not isinstance(
result, (asyncio.TimeoutError, ClientResponseError, CannotConnect)
result, asyncio.TimeoutError | ClientResponseError | CannotConnect
):
_LOGGER.warning(
"Unexpected exception during initial sync: %s",
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/broadlink/updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ async def async_update(self):
except (BroadlinkException, OSError) as err:
if self.available and (
dt.utcnow() - self.last_update > self.SCAN_INTERVAL * 3
or isinstance(err, (AuthorizationError, OSError))
or isinstance(err, AuthorizationError | OSError)
):
self.available = False
_LOGGER.warning(
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/calendar/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ def _event_dict_factory(obj: Iterable[tuple[str, Any]]) -> dict[str, str]:
"""Convert CalendarEvent dataclass items to dictionary of attributes."""
result: dict[str, str] = {}
for name, value in obj:
if isinstance(value, (datetime.datetime, datetime.date)):
if isinstance(value, datetime.datetime | datetime.date):
result[name] = value.isoformat()
elif value is not None:
result[name] = str(value)
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/datadog/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def state_changed_listener(event):
tags = [f"entity:{state.entity_id}"]

for key, value in states.items():
if isinstance(value, (float, int)):
if isinstance(value, float | int):
attribute = f"{metric}.{key.replace(' ', '_')}"
value = int(value) if isinstance(value, bool) else value
statsd.gauge(attribute, value, sample_rate=sample_rate, tags=tags)
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/derivative/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,5 +263,5 @@ def native_value(self) -> float | int | Decimal:
"""Return the state of the sensor."""
value = round(self._state, self._round_digits)
if TYPE_CHECKING:
assert isinstance(value, (float, int, Decimal))
assert isinstance(value, float | int | Decimal)
return value
2 changes: 1 addition & 1 deletion homeassistant/components/diagnostics/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def async_redact_data(data: _T, to_redact: Iterable[Any]) -> _T:
@callback
def async_redact_data(data: _T, to_redact: Iterable[Any]) -> _T:
"""Redact sensitive data in a dict."""
if not isinstance(data, (Mapping, list)):
if not isinstance(data, Mapping | list):
return data

if isinstance(data, list):
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/duckdns/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ def async_track_time_interval_backoff(
intervals,
) -> CALLBACK_TYPE:
"""Add a listener that fires repetitively at every timedelta interval."""
if not isinstance(intervals, (list, tuple)):
if not isinstance(intervals, list | tuple):
intervals = (intervals,)
remove = None
failed = 0
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 @@ -659,9 +659,9 @@ def set_auto_temp_hold(self, heat_temp, cool_temp):
_LOGGER.debug(
"Setting ecobee hold_temp to: heat=%s, is=%s, cool=%s, is=%s",
heat_temp,
isinstance(heat_temp, (int, float)),
isinstance(heat_temp, int | float),
cool_temp,
isinstance(cool_temp, (int, float)),
isinstance(cool_temp, int | float),
)

self.update_without_throttle = True
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/emulated_kasa/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def get_plug_devices(hass, entity_configs):
if state.state == STATE_ON or state.domain == SENSOR_DOMAIN:
if CONF_POWER in entity_config:
power_val = entity_config[CONF_POWER]
if isinstance(power_val, (float, int)):
if isinstance(power_val, float | int):
power = float(power_val)
elif isinstance(power_val, str):
power = float(hass.states.get(power_val).state)
Expand Down
8 changes: 3 additions & 5 deletions homeassistant/components/esphome/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -351,11 +351,9 @@ async def on_connect_error(err: Exception) -> None:
"""Start reauth flow if appropriate connect error type."""
if isinstance(
err,
(
RequiresEncryptionAPIError,
InvalidEncryptionKeyAPIError,
InvalidAuthAPIError,
),
RequiresEncryptionAPIError
| InvalidEncryptionKeyAPIError
| InvalidAuthAPIError,
):
entry.async_start_reauth(hass)

Expand Down
2 changes: 2 additions & 0 deletions homeassistant/components/esphome/bluetooth/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,7 @@ async def read_gatt_char(
The characteristic to read from, specified by either integer
handle, UUID or directly by the BleakGATTCharacteristic
object representing it.
**kwargs: Unused
Copy link
Contributor Author

@epenet epenet Mar 7, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This file resolves D417 Missing argument description in the docstring
All others refer to UP038 [*] Use 'X | Y' in 'isinstance' call instead of '(X, Y)'


Returns:
(bytearray) The read data.
Expand All @@ -542,6 +543,7 @@ async def read_gatt_descriptor(self, handle: int, **kwargs: Any) -> bytearray:

Args:
handle (int): The handle of the descriptor to read from.
**kwargs: Unused

Returns:
(bytearray) The read data.
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/graphite/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ def _report_attributes(self, entity_id, new_state):
"%s.%s.%s %f %i"
% (self._prefix, entity_id, key.replace(" ", "_"), value, now)
for key, value in things.items()
if isinstance(value, (float, int))
if isinstance(value, float | int)
]
if not lines:
return
Expand Down
8 changes: 4 additions & 4 deletions homeassistant/components/hdmi_cec/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ def parse_mapping(mapping, parents=None):
if parents is None:
parents = []
for addr, val in mapping.items():
if isinstance(addr, (str,)) and isinstance(val, (str,)):
if isinstance(addr, str) and isinstance(val, str):
yield (addr, PhysicalAddress(val))
else:
cur = parents + [addr]
Expand Down Expand Up @@ -243,7 +243,7 @@ def _volume(call: ServiceCall) -> None:
_LOGGER.warning("Unknown command %s", cmd)

def _process_volume(cmd, att):
if isinstance(att, (str,)):
if isinstance(att, str):
att = att.strip()
if att == CMD_PRESS:
hdmi_network.send_command(KeyPressCommand(cmd, dst=ADDR_AUDIOSYSTEM))
Expand All @@ -269,7 +269,7 @@ def _tx(call: ServiceCall) -> None:
_LOGGER.error("Attribute 'cmd' is missing")
return
if ATTR_ATT in data:
if isinstance(data[ATTR_ATT], (list,)):
if isinstance(data[ATTR_ATT], list):
att = data[ATTR_ATT]
else:
att = reduce(lambda x, y: f"{x}:{y:x}", data[ATTR_ATT])
Expand Down Expand Up @@ -302,7 +302,7 @@ def _select_device(call: ServiceCall) -> None:
"Device %s has not physical address", call.data[ATTR_DEVICE]
)
return
if not isinstance(addr, (PhysicalAddress,)):
if not isinstance(addr, PhysicalAddress):
addr = PhysicalAddress(addr)
hdmi_network.active_source(addr)
_LOGGER.info("Selected %s (%s)", call.data[ATTR_DEVICE], addr)
Expand Down
4 changes: 2 additions & 2 deletions homeassistant/components/homekit/type_covers.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ def async_update_state(self, new_state):
if not self._supports_tilt:
return
current_tilt = new_state.attributes.get(ATTR_CURRENT_TILT_POSITION)
if not isinstance(current_tilt, (float, int)):
if not isinstance(current_tilt, float | int):
return
# HomeKit sends values between -90 and 90.
# We'll have to normalize to [0,100]
Expand Down Expand Up @@ -311,7 +311,7 @@ def move_cover(self, value):
def async_update_state(self, new_state: State) -> None:
"""Update cover position and tilt after state changed."""
current_position = new_state.attributes.get(ATTR_CURRENT_POSITION)
if isinstance(current_position, (float, int)):
if isinstance(current_position, float | int):
current_position = int(current_position)
self.char_current_position.set_value(current_position)
# Writing target_position on a moving cover
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/homekit/type_humidifiers.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,5 +250,5 @@ def async_update_state(self, new_state):

# Update target humidity
target_humidity = new_state.attributes.get(ATTR_HUMIDITY)
if isinstance(target_humidity, (int, float)):
if isinstance(target_humidity, int | float):
self.char_target_humidity.set_value(target_humidity)
6 changes: 3 additions & 3 deletions homeassistant/components/homekit/type_lights.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ def async_update_state(self, new_state):
if (
self.brightness_supported
and (brightness := attributes.get(ATTR_BRIGHTNESS)) is not None
and isinstance(brightness, (int, float))
and isinstance(brightness, int | float)
):
brightness = round(brightness / 255 * 100, 0)
# The homeassistant component might report its brightness as 0 but is
Expand Down Expand Up @@ -267,7 +267,7 @@ def async_update_state(self, new_state):
hue, saturation = 0, 0
else:
hue, saturation = attributes.get(ATTR_HS_COLOR, (None, None))
if isinstance(hue, (int, float)) and isinstance(saturation, (int, float)):
if isinstance(hue, int | float) and isinstance(saturation, int | float):
self.char_hue.set_value(round(hue, 0))
self.char_saturation.set_value(round(saturation, 0))
if color_mode_changed:
Expand All @@ -284,7 +284,7 @@ def async_update_state(self, new_state):
color_temp = color_temperature_kelvin_to_mired(color_temp_kelvin)
elif color_mode == ColorMode.WHITE:
color_temp = self.min_mireds
if isinstance(color_temp, (int, float)):
if isinstance(color_temp, int | float):
self.char_color_temp.set_value(round(color_temp, 0))
if color_mode_changed:
self.char_color_temp.notify()
16 changes: 8 additions & 8 deletions homeassistant/components/homekit/type_thermostats.py
Original file line number Diff line number Diff line change
Expand Up @@ -633,26 +633,26 @@ def _async_update_state(self, new_state):
# Update current humidity
if CHAR_CURRENT_HUMIDITY in self.chars:
current_humdity = attributes.get(ATTR_CURRENT_HUMIDITY)
if isinstance(current_humdity, (int, float)):
if isinstance(current_humdity, int | float):
self.char_current_humidity.set_value(current_humdity)

# Update target humidity
if CHAR_TARGET_HUMIDITY in self.chars:
target_humdity = attributes.get(ATTR_HUMIDITY)
if isinstance(target_humdity, (int, float)):
if isinstance(target_humdity, int | float):
self.char_target_humidity.set_value(target_humdity)

# Update cooling threshold temperature if characteristic exists
if self.char_cooling_thresh_temp:
cooling_thresh = attributes.get(ATTR_TARGET_TEMP_HIGH)
if isinstance(cooling_thresh, (int, float)):
if isinstance(cooling_thresh, int | float):
cooling_thresh = self._temperature_to_homekit(cooling_thresh)
self.char_cooling_thresh_temp.set_value(cooling_thresh)

# Update heating threshold temperature if characteristic exists
if self.char_heating_thresh_temp:
heating_thresh = attributes.get(ATTR_TARGET_TEMP_LOW)
if isinstance(heating_thresh, (int, float)):
if isinstance(heating_thresh, int | float):
heating_thresh = self._temperature_to_homekit(heating_thresh)
self.char_heating_thresh_temp.set_value(heating_thresh)

Expand All @@ -667,11 +667,11 @@ def _async_update_state(self, new_state):
hc_hvac_mode = self.char_target_heat_cool.value
if hc_hvac_mode == HC_HEAT_COOL_HEAT:
temp_low = attributes.get(ATTR_TARGET_TEMP_LOW)
if isinstance(temp_low, (int, float)):
if isinstance(temp_low, int | float):
target_temp = self._temperature_to_homekit(temp_low)
elif hc_hvac_mode == HC_HEAT_COOL_COOL:
temp_high = attributes.get(ATTR_TARGET_TEMP_HIGH)
if isinstance(temp_high, (int, float)):
if isinstance(temp_high, int | float):
target_temp = self._temperature_to_homekit(temp_high)
if target_temp:
self.char_target_temp.set_value(target_temp)
Expand Down Expand Up @@ -836,14 +836,14 @@ def _get_temperature_range_from_state(state, unit, default_min, default_max):
def _get_target_temperature(state, unit):
"""Calculate the target temperature from a state."""
target_temp = state.attributes.get(ATTR_TEMPERATURE)
if isinstance(target_temp, (int, float)):
if isinstance(target_temp, int | float):
return temperature_to_homekit(target_temp, unit)
return None


def _get_current_temperature(state, unit):
"""Calculate the current temperature from a state."""
target_temp = state.attributes.get(ATTR_CURRENT_TEMPERATURE)
if isinstance(target_temp, (int, float)):
if isinstance(target_temp, int | float):
return temperature_to_homekit(target_temp, unit)
return None
18 changes: 7 additions & 11 deletions homeassistant/components/homematicip_cloud/binary_sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,24 +94,20 @@ async def async_setup_entry(
entities.append(
HomematicipMultiContactInterface(hap, device, channel=channel)
)
elif isinstance(
device, (AsyncContactInterface, AsyncFullFlushContactInterface)
):
elif isinstance(device, AsyncContactInterface | AsyncFullFlushContactInterface):
entities.append(HomematicipContactInterface(hap, device))
if isinstance(
device,
(AsyncShutterContact, AsyncShutterContactMagnetic),
AsyncShutterContact | AsyncShutterContactMagnetic,
):
entities.append(HomematicipShutterContact(hap, device))
if isinstance(device, AsyncRotaryHandleSensor):
entities.append(HomematicipShutterContact(hap, device, True))
if isinstance(
device,
(
AsyncMotionDetectorIndoor,
AsyncMotionDetectorOutdoor,
AsyncMotionDetectorPushButton,
),
AsyncMotionDetectorIndoor
| AsyncMotionDetectorOutdoor
| AsyncMotionDetectorPushButton,
):
entities.append(HomematicipMotionDetector(hap, device))
if isinstance(device, AsyncPluggableMainsFailureSurveillance):
Expand All @@ -125,11 +121,11 @@ async def async_setup_entry(
if isinstance(device, AsyncWaterSensor):
entities.append(HomematicipWaterDetector(hap, device))
if isinstance(
device, (AsyncRainSensor, AsyncWeatherSensorPlus, AsyncWeatherSensorPro)
device, AsyncRainSensor | AsyncWeatherSensorPlus | AsyncWeatherSensorPro
):
entities.append(HomematicipRainSensor(hap, device))
if isinstance(
device, (AsyncWeatherSensor, AsyncWeatherSensorPlus, AsyncWeatherSensorPro)
device, AsyncWeatherSensor | AsyncWeatherSensorPlus | AsyncWeatherSensorPro
):
entities.append(HomematicipStormSensor(hap, device))
entities.append(HomematicipSunshineSensor(hap, device))
Expand Down
8 changes: 3 additions & 5 deletions homeassistant/components/homematicip_cloud/climate.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,11 +325,9 @@ def _first_radiator_thermostat(
for device in self._device.devices:
if isinstance(
device,
(
AsyncHeatingThermostat,
AsyncHeatingThermostatCompact,
AsyncHeatingThermostatEvo,
),
AsyncHeatingThermostat
| AsyncHeatingThermostatCompact
| AsyncHeatingThermostatEvo,
):
return device

Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/homematicip_cloud/cover.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ async def async_setup_entry(
elif isinstance(device, AsyncFullFlushShutter):
entities.append(HomematicipCoverShutter(hap, device))
elif isinstance(
device, (AsyncHoermannDrivesModule, AsyncGarageDoorModuleTormatic)
device, AsyncHoermannDrivesModule | AsyncGarageDoorModuleTormatic
):
entities.append(HomematicipGarageDoorModule(hap, device))

Expand Down
7 changes: 5 additions & 2 deletions homeassistant/components/homematicip_cloud/light.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,15 @@ async def async_setup_entry(
hap, device, device.bottomLightChannelIndex
)
)
elif isinstance(device, (AsyncWiredDimmer3, AsyncDinRailDimmer3)):
elif isinstance(device, AsyncWiredDimmer3 | AsyncDinRailDimmer3):
for channel in range(1, 4):
entities.append(HomematicipMultiDimmer(hap, device, channel=channel))
elif isinstance(
device,
(AsyncDimmer, AsyncPluggableDimmer, AsyncBrandDimmer, AsyncFullFlushDimmer),
AsyncDimmer
| AsyncPluggableDimmer
| AsyncBrandDimmer
| AsyncFullFlushDimmer,
):
entities.append(HomematicipDimmer(hap, device))

Expand Down
Loading