Enable SIM114 ruff rule (#111125)

This commit is contained in:
Joost Lekkerkerker 2024-02-23 13:21:59 +01:00 committed by GitHub
parent 26fac184b4
commit 730d805876
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
26 changed files with 135 additions and 160 deletions

View File

@ -325,9 +325,7 @@ class ArcamFmj(MediaPlayerEntity):
def media_content_type(self) -> MediaType | None:
"""Content type of current playing media."""
source = self._state.get_source()
if source == SourceCodes.DAB:
value = MediaType.MUSIC
elif source == SourceCodes.FM:
if source in (SourceCodes.DAB, SourceCodes.FM):
value = MediaType.MUSIC
else:
value = None

View File

@ -294,10 +294,7 @@ async def parse_m3u(hass, url):
continue
length = info[0].split(" ", 1)
title = info[1].strip()
elif line.startswith("#EXT-X-VERSION:"):
# HLS stream, supported by cast devices
raise PlaylistSupported("HLS")
elif line.startswith("#EXT-X-STREAM-INF:"):
elif line.startswith(("#EXT-X-VERSION:", "#EXT-X-STREAM-INF:")):
# HLS stream, supported by cast devices
raise PlaylistSupported("HLS")
elif line.startswith("#"):

View File

@ -76,12 +76,11 @@ async def update_listener(hass: HomeAssistant, config_entry: ConfigEntry) -> Non
# Remove orphaned entities
for entity in entities:
currency = entity.unique_id.split("-")[-1]
if "xe" in entity.unique_id and currency not in config_entry.options.get(
CONF_EXCHANGE_RATES, []
):
registry.async_remove(entity.entity_id)
elif "wallet" in entity.unique_id and currency not in config_entry.options.get(
CONF_CURRENCIES, []
if (
"xe" in entity.unique_id
and currency not in config_entry.options.get(CONF_EXCHANGE_RATES, [])
or "wallet" in entity.unique_id
and currency not in config_entry.options.get(CONF_CURRENCIES, [])
):
registry.async_remove(entity.entity_id)

View File

@ -355,20 +355,19 @@ class EnergyCostSensor(SensorEntity):
return
if (
state_class != SensorStateClass.TOTAL_INCREASING
and energy_state.attributes.get(ATTR_LAST_RESET)
!= self._last_energy_sensor_state.attributes.get(ATTR_LAST_RESET)
):
# Energy meter was reset, reset cost sensor too
energy_state_copy = copy.copy(energy_state)
energy_state_copy.state = "0.0"
self._reset(energy_state_copy)
elif state_class == SensorStateClass.TOTAL_INCREASING and reset_detected(
self.hass,
cast(str, self._config[self._adapter.stat_energy_key]),
energy,
float(self._last_energy_sensor_state.state),
self._last_energy_sensor_state,
(
state_class != SensorStateClass.TOTAL_INCREASING
and energy_state.attributes.get(ATTR_LAST_RESET)
!= self._last_energy_sensor_state.attributes.get(ATTR_LAST_RESET)
)
or state_class == SensorStateClass.TOTAL_INCREASING
and reset_detected(
self.hass,
cast(str, self._config[self._adapter.stat_energy_key]),
energy,
float(self._last_energy_sensor_state.state),
self._last_energy_sensor_state,
)
):
# Energy meter was reset, reset cost sensor too
energy_state_copy = copy.copy(energy_state)

View File

@ -160,9 +160,7 @@ class EnvisalinkAlarm(EnvisalinkDevice, AlarmControlPanelEntity):
state = STATE_ALARM_ARMED_AWAY
elif self._info["status"]["armed_stay"]:
state = STATE_ALARM_ARMED_HOME
elif self._info["status"]["exit_delay"]:
state = STATE_ALARM_PENDING
elif self._info["status"]["entry_delay"]:
elif self._info["status"]["exit_delay"] or self._info["status"]["entry_delay"]:
state = STATE_ALARM_PENDING
elif self._info["status"]["alpha"]:
state = STATE_ALARM_DISARMED

View File

@ -143,10 +143,7 @@ class FibaroThermostat(FibaroDevice, ClimateEntity):
for device in siblings:
# Detecting temperature device, one strong and one weak way of
# doing so, so we prefer the hard evidence, if there is such.
if device.type == "com.fibaro.temperatureSensor":
self._temp_sensor_device = FibaroDevice(device)
tempunit = device.unit
elif (
if device.type == "com.fibaro.temperatureSensor" or (
self._temp_sensor_device is None
and device.has_unit
and (device.value.has_value or device.has_heating_thermostat_setpoint)

View File

@ -1942,9 +1942,7 @@ class ModesTrait(_Trait):
elif self.state.domain == media_player.DOMAIN:
if media_player.ATTR_SOUND_MODE_LIST in attrs:
mode_settings["sound mode"] = attrs.get(media_player.ATTR_SOUND_MODE)
elif self.state.domain == input_select.DOMAIN:
mode_settings["option"] = self.state.state
elif self.state.domain == select.DOMAIN:
elif self.state.domain in (input_select.DOMAIN, select.DOMAIN):
mode_settings["option"] = self.state.state
elif self.state.domain == humidifier.DOMAIN:
if ATTR_MODE in attrs:

View File

@ -69,16 +69,15 @@ async def async_setup_entry(
elif isinstance(device, AsyncOpenCollector8Module):
for channel in range(1, 9):
entities.append(HomematicipMultiSwitch(hap, device, channel=channel))
elif isinstance(device, AsyncHeatingSwitch2):
for channel in range(1, 3):
entities.append(HomematicipMultiSwitch(hap, device, channel=channel))
elif isinstance(device, AsyncMultiIOBox):
for channel in range(1, 3):
entities.append(HomematicipMultiSwitch(hap, device, channel=channel))
elif isinstance(device, AsyncPrintedCircuitBoardSwitch2):
for channel in range(1, 3):
entities.append(HomematicipMultiSwitch(hap, device, channel=channel))
elif isinstance(device, AsyncBrandSwitch2):
elif isinstance(
device,
(
AsyncBrandSwitch2,
AsyncPrintedCircuitBoardSwitch2,
AsyncHeatingSwitch2,
AsyncMultiIOBox,
),
):
for channel in range(1, 3):
entities.append(HomematicipMultiSwitch(hap, device, channel=channel))

View File

@ -232,15 +232,11 @@ class IndexSensor(IQVIAEntity, SensorEntity):
if self.entity_description.key in (
TYPE_ALLERGY_TODAY,
TYPE_ALLERGY_TOMORROW,
):
data = self.coordinator.data.get("Location")
elif self.entity_description.key in (
TYPE_ASTHMA_TODAY,
TYPE_ASTHMA_TOMORROW,
TYPE_DISEASE_TODAY,
):
data = self.coordinator.data.get("Location")
elif self.entity_description.key == TYPE_DISEASE_TODAY:
data = self.coordinator.data.get("Location")
except KeyError:
return

View File

@ -65,9 +65,7 @@ class Itunes:
try:
if method == "GET":
response = requests.get(url, timeout=DEFAULT_TIMEOUT)
elif method == "POST":
response = requests.put(url, params, timeout=DEFAULT_TIMEOUT)
elif method == "PUT":
elif method in ("POST", "PUT"):
response = requests.put(url, params, timeout=DEFAULT_TIMEOUT)
elif method == "DELETE":
response = requests.delete(url, timeout=DEFAULT_TIMEOUT)

View File

@ -292,9 +292,7 @@ class KNXCommonFlow(ABC, FlowHandler):
else:
if bool(self._selected_tunnel.tunnelling_requires_secure) is not (
selected_tunnelling_type == CONF_KNX_TUNNELING_TCP_SECURE
):
errors[CONF_KNX_TUNNELING_TYPE] = "unsupported_tunnel_type"
elif (
) or (
selected_tunnelling_type == CONF_KNX_TUNNELING_TCP
and not self._selected_tunnel.supports_tunnelling_tcp
):

View File

@ -126,13 +126,17 @@ class FlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
async_get_clientsession(self.hass),
)
except (ClientResponseError, AttributeError) as err:
if isinstance(err, ClientResponseError) and err.status in (
HTTPStatus.UNAUTHORIZED,
HTTPStatus.FORBIDDEN,
if (
isinstance(err, ClientResponseError)
and err.status
in (
HTTPStatus.UNAUTHORIZED,
HTTPStatus.FORBIDDEN,
)
or isinstance(err, AttributeError)
and err.name == "get"
):
errors["base"] = "invalid_auth"
elif isinstance(err, AttributeError) and err.name == "get":
errors["base"] = "invalid_auth"
else:
errors["base"] = "cannot_connect"
except (

View File

@ -100,9 +100,7 @@ class NessAlarmPanel(alarm.AlarmControlPanelEntity):
self._attr_state = None
elif arming_state == ArmingState.DISARMED:
self._attr_state = STATE_ALARM_DISARMED
elif arming_state == ArmingState.ARMING:
self._attr_state = STATE_ALARM_ARMING
elif arming_state == ArmingState.EXIT_DELAY:
elif arming_state in (ArmingState.ARMING, ArmingState.EXIT_DELAY):
self._attr_state = STATE_ALARM_ARMING
elif arming_state == ArmingState.ARMED:
self._attr_state = ARMING_MODE_TO_STATE.get(

View File

@ -197,13 +197,11 @@ class NetdataAlarms(SensorEntity):
_LOGGER.debug("Host %s has %s alarms", self.name, number_of_alarms)
for alarm in alarms:
if alarms[alarm]["recipient"] == "silent":
number_of_relevant_alarms = number_of_relevant_alarms - 1
elif alarms[alarm]["status"] == "CLEAR":
number_of_relevant_alarms = number_of_relevant_alarms - 1
elif alarms[alarm]["status"] == "UNDEFINED":
number_of_relevant_alarms = number_of_relevant_alarms - 1
elif alarms[alarm]["status"] == "UNINITIALIZED":
if alarms[alarm]["recipient"] == "silent" or alarms[alarm]["status"] in (
"CLEAR",
"UNDEFINED",
"UNINITIALIZED",
):
number_of_relevant_alarms = number_of_relevant_alarms - 1
elif alarms[alarm]["status"] == "CRITICAL":
self._state = "critical"

View File

@ -32,9 +32,7 @@ class OPNSenseDeviceScanner(DeviceScanner):
"""Create dict with mac address keys from list of devices."""
out_devices = {}
for device in devices:
if not self.interfaces:
out_devices[device["mac"]] = device
elif device["intf_description"] in self.interfaces:
if not self.interfaces or device["intf_description"] in self.interfaces:
out_devices[device["mac"]] = device
return out_devices

View File

@ -116,11 +116,8 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
{"protocol": data["protocol"], "uuid": data["uuid"]}, **data["message"]
)
# No whitelist defined, put data on event bus
if not whitelist:
hass.bus.fire(EVENT, data)
# Check if data matches the defined whitelist
elif all(str(data[key]) in whitelist[key] for key in whitelist):
# No whitelist defined or data matches whitelist, put data on event bus
if not whitelist or all(str(data[key]) in whitelist[key] for key in whitelist):
hass.bus.fire(EVENT, data)
pilight_client.set_callback(handle_received_code)

View File

@ -267,10 +267,11 @@ class RMVDepartureData:
if not dest_found:
continue
elif self._lines and journey["number"] not in self._lines:
continue
elif journey["minutes"] < self._time_offset:
elif (
self._lines
and journey["number"] not in self._lines
or journey["minutes"] < self._time_offset
):
continue
for attr in ("direction", "departure_time", "product", "minutes"):

View File

@ -268,9 +268,10 @@ class RoonDevice(MediaPlayerEntity):
break
# determine player state
if not new_state:
if self.player_data["state"] == "playing":
new_state = MediaPlayerState.PLAYING
elif self.player_data["state"] == "loading":
if (
self.player_data["state"] == "playing"
or self.player_data["state"] == "loading"
):
new_state = MediaPlayerState.PLAYING
elif self.player_data["state"] == "stopped":
new_state = MediaPlayerState.IDLE

View File

@ -60,10 +60,10 @@ class SharkIqUpdateCoordinator(DataUpdateCoordinator[bool]): # pylint: disable=
async def _async_update_data(self) -> bool:
"""Update data device by device."""
try:
if self.ayla_api.token_expiring_soon:
await self.ayla_api.async_refresh_auth()
elif datetime.now() > self.ayla_api.auth_expiration - timedelta(
seconds=600
if (
self.ayla_api.token_expiring_soon
or datetime.now()
> self.ayla_api.auth_expiration - timedelta(seconds=600)
):
await self.ayla_api.async_refresh_auth()

View File

@ -273,13 +273,13 @@ class SnmpSwitch(SwitchEntity):
)
else:
for resrow in restable:
if resrow[-1] == self._payload_on:
if resrow[-1] == self._payload_on or resrow[-1] == Integer(
self._payload_on
):
self._state = True
elif resrow[-1] == Integer(self._payload_on):
self._state = True
elif resrow[-1] == self._payload_off:
self._state = False
elif resrow[-1] == Integer(self._payload_off):
elif resrow[-1] == self._payload_off or resrow[-1] == Integer(
self._payload_off
):
self._state = False
else:
self._state = None

View File

@ -381,12 +381,14 @@ class StatisticsSensor(SensorEntity):
unit = None
elif self._state_characteristic in STATS_NUMERIC_RETAIN_UNIT:
unit = base_unit
elif self._state_characteristic in STATS_NOT_A_NUMBER:
unit = None
elif self._state_characteristic in (
STAT_COUNT,
STAT_COUNT_BINARY_ON,
STAT_COUNT_BINARY_OFF,
elif (
self._state_characteristic in STATS_NOT_A_NUMBER
or self._state_characteristic
in (
STAT_COUNT,
STAT_COUNT_BINARY_ON,
STAT_COUNT_BINARY_OFF,
)
):
unit = None
elif self._state_characteristic == STAT_VARIANCE:

View File

@ -92,13 +92,15 @@ class TuyaVacuumEntity(TuyaEntity, StateVacuumEntity):
if self.find_dpcode(DPCode.PAUSE, prefer_function=True):
self._attr_supported_features |= VacuumEntityFeature.PAUSE
if self.find_dpcode(DPCode.SWITCH_CHARGE, prefer_function=True):
self._attr_supported_features |= VacuumEntityFeature.RETURN_HOME
elif (
enum_type := self.find_dpcode(
DPCode.MODE, dptype=DPType.ENUM, prefer_function=True
if (
self.find_dpcode(DPCode.SWITCH_CHARGE, prefer_function=True)
or (
enum_type := self.find_dpcode(
DPCode.MODE, dptype=DPType.ENUM, prefer_function=True
)
)
) and TUYA_MODE_RETURN_HOME in enum_type.range:
and TUYA_MODE_RETURN_HOME in enum_type.range
):
self._attr_supported_features |= VacuumEntityFeature.RETURN_HOME
if self.find_dpcode(DPCode.SEEK, prefer_function=True):

View File

@ -85,9 +85,10 @@ class VeraSensor(VeraDevice[veraApi.VeraSensor], SensorEntity):
else:
self._attr_native_unit_of_measurement = UnitOfTemperature.CELSIUS
elif self.vera_device.category == veraApi.CATEGORY_LIGHT_SENSOR:
self._attr_native_value = self.vera_device.light
elif self.vera_device.category == veraApi.CATEGORY_UV_SENSOR:
elif self.vera_device.category in (
veraApi.CATEGORY_LIGHT_SENSOR,
veraApi.CATEGORY_UV_SENSOR,
):
self._attr_native_value = self.vera_device.light
elif self.vera_device.category == veraApi.CATEGORY_HUMIDITY_SENSOR:
self._attr_native_value = self.vera_device.humidity

View File

@ -410,18 +410,15 @@ class ZwaveLight(ZWaveBaseEntity, LightEntity):
@callback
def _calculate_color_support(self) -> None:
"""Calculate light colors."""
(red_val, green_val, blue_val, ww_val, cw_val) = self._get_color_values()
(red, green, blue, warm_white, cool_white) = self._get_color_values()
# RGB support
if red_val and green_val and blue_val:
if red and green and blue:
self._supports_color = True
# color temperature support
if ww_val and cw_val:
if warm_white and cool_white:
self._supports_color_temp = True
# only one white channel (warm white) = rgbw support
elif red_val and green_val and blue_val and ww_val:
self._supports_rgbw = True
# only one white channel (cool white) = rgbw support
elif cw_val:
# only one white channel (warm white or cool white) = rgbw support
elif red and green and blue and warm_white or cool_white:
self._supports_rgbw = True
@callback

View File

@ -221,9 +221,7 @@ class RegistryEntry:
if not self.name and self.has_entity_name:
display_dict["en"] = self.original_name
if self.domain == "sensor" and (sensor_options := self.options.get("sensor")):
if (precision := sensor_options.get("display_precision")) is not None:
display_dict["dp"] = precision
elif (
if (precision := sensor_options.get("display_precision")) is not None or (
precision := sensor_options.get("suggested_display_precision")
) is not None:
display_dict["dp"] = precision

View File

@ -583,20 +583,20 @@ select = [
"B023", # Function definition does not bind loop variable {name}
"B026", # Star-arg unpacking after a keyword argument is strongly discouraged
"B904", # Use raise from to specify exception cause
"C", # complexity
"C", # complexity
"COM818", # Trailing comma on bare tuple prohibited
"D", # docstrings
"DTZ003", # Use datetime.now(tz=) instead of datetime.utcnow()
"DTZ004", # Use datetime.fromtimestamp(ts, tz=) instead of datetime.utcfromtimestamp(ts)
"E", # pycodestyle
"F", # pyflakes/autoflake
"D", # docstrings
"DTZ003", # Use datetime.now(tz=) instead of datetime.utcnow()
"DTZ004", # Use datetime.fromtimestamp(ts, tz=) instead of datetime.utcfromtimestamp(ts)
"E", # pycodestyle
"F", # pyflakes/autoflake
"G", # flake8-logging-format
"I", # isort
"I", # isort
"ICN001", # import concentions; {name} should be imported as {asname}
"N804", # First argument of a class method should be named cls
"N805", # First argument of a method should be named self
"N815", # Variable {name} in class scope should not be mixedCase
"PGH004", # Use specific rule codes when using noqa
"PGH004", # Use specific rule codes when using noqa
"PLC0414", # Useless import alias. Import alias does not rename original package.
"PLC", # pylint
"PLE", # pylint
@ -605,24 +605,25 @@ select = [
"Q000", # Double quotes found but single quotes preferred
"RUF006", # Store a reference to the return value of asyncio.create_task
"S102", # Use of exec detected
"S103", # bad-file-permissions
"S108", # hardcoded-temp-file
"S306", # suspicious-mktemp-usage
"S307", # suspicious-eval-usage
"S313", # suspicious-xmlc-element-tree-usage
"S314", # suspicious-xml-element-tree-usage
"S315", # suspicious-xml-expat-reader-usage
"S316", # suspicious-xml-expat-builder-usage
"S317", # suspicious-xml-sax-usage
"S318", # suspicious-xml-mini-dom-usage
"S319", # suspicious-xml-pull-dom-usage
"S320", # suspicious-xmle-tree-usage
"S601", # paramiko-call
"S602", # subprocess-popen-with-shell-equals-true
"S604", # call-with-shell-equals-true
"S608", # hardcoded-sql-expression
"S609", # unix-command-wildcard-injection
"S103", # bad-file-permissions
"S108", # hardcoded-temp-file
"S306", # suspicious-mktemp-usage
"S307", # suspicious-eval-usage
"S313", # suspicious-xmlc-element-tree-usage
"S314", # suspicious-xml-element-tree-usage
"S315", # suspicious-xml-expat-reader-usage
"S316", # suspicious-xml-expat-builder-usage
"S317", # suspicious-xml-sax-usage
"S318", # suspicious-xml-mini-dom-usage
"S319", # suspicious-xml-pull-dom-usage
"S320", # suspicious-xmle-tree-usage
"S601", # paramiko-call
"S602", # subprocess-popen-with-shell-equals-true
"S604", # call-with-shell-equals-true
"S608", # hardcoded-sql-expression
"S609", # unix-command-wildcard-injection
"SIM105", # Use contextlib.suppress({exception}) instead of try-except-pass
"SIM114", # Combine if branches using logical or operator
"SIM117", # Merge with-statements that use the same scope
"SIM118", # Use {key} in {dict} instead of {key} in {dict}.keys()
"SIM201", # Use {left} != {right} instead of not {left} == {right}
@ -631,22 +632,22 @@ select = [
"SIM300", # Yoda conditions. Use 'age == 42' instead of '42 == age'.
"SIM401", # Use get from dict with default instead of an if block
"T100", # Trace found: {name} used
"T20", # flake8-print
"T20", # flake8-print
"TID251", # Banned imports
"TRY004", # Prefer TypeError exception for invalid type
"TRY302", # Remove exception handler; error is immediately re-raised
"UP", # pyupgrade
"W", # pycodestyle
"UP", # pyupgrade
"W", # pycodestyle
]
ignore = [
"D202", # No blank lines allowed after function docstring
"D203", # 1 blank line required before class docstring
"D213", # Multi-line docstring summary should start at the second line
"D406", # Section name should end with a newline
"D407", # Section name underlining
"E501", # line too long
"E731", # do not assign a lambda expression, use a def
"D202", # No blank lines allowed after function docstring
"D203", # 1 blank line required before class docstring
"D213", # Multi-line docstring summary should start at the second line
"D406", # Section name should end with a newline
"D407", # Section name underlining
"E501", # line too long
"E731", # do not assign a lambda expression, use a def
# Ignore ignored, as the rule is now back in preview/nursery, which cannot
# be ignored anymore without warnings.
@ -659,7 +660,7 @@ ignore = [
"PLR0912", # Too many branches ({branches} > {max_branches})
"PLR0913", # Too many arguments to function call ({c_args} > {max_args})
"PLR0915", # Too many statements ({statements} > {max_statements})
"PLR2004", # Magic value used in comparison, consider replacing {value} with a constant variable
"PLR2004", # Magic value used in comparison, consider replacing {value} with a constant variable
"PLW2901", # Outer {outer_kind} variable {name} overwritten by inner {inner_kind} target
"UP006", # keep type annotation style as is
"UP007", # keep type annotation style as is