From cddce0ce0d84cbe635aeac194f03289365599cc9 Mon Sep 17 00:00:00 2001 From: Joost Lekkerkerker Date: Mon, 11 Mar 2024 04:20:37 +0100 Subject: [PATCH] Enable more SIM ruff rules (#113015) * SIM101 SIM103 * SIM107 SIM109 * SIM110 * SIM112 SIM113 * SIM115 * SIM116 * Fix * Fix * Fix --- homeassistant/components/fritz/common.py | 5 +---- .../components/homematicip_cloud/climate.py | 6 +----- homeassistant/components/mqtt/event.py | 3 +-- .../components/philips_js/binary_sensor.py | 5 +---- homeassistant/helpers/intent.py | 6 +----- pylint/plugins/hass_enforce_type_hints.py | 5 +---- pyproject.toml | 8 ++++++++ script/hassfest/config_schema.py | 5 +---- tests/components/litterrobot/test_select.py | 13 +++++-------- tests/components/litterrobot/test_switch.py | 6 ++---- tests/components/media_extractor/test_init.py | 13 ++++++------- tests/components/mqtt/test_common.py | 4 +--- tests/components/template/test_fan.py | 14 +++++++------- tests/components/zha/test_cluster_handlers.py | 2 +- tests/components/zha/test_device_trigger.py | 5 +---- tests/components/zha/test_discover.py | 5 +---- tests/helpers/test_check_config.py | 6 ++---- 17 files changed, 41 insertions(+), 70 deletions(-) diff --git a/homeassistant/components/fritz/common.py b/homeassistant/components/fritz/common.py index f3468a0a161..39b3c8fbc20 100644 --- a/homeassistant/components/fritz/common.py +++ b/homeassistant/components/fritz/common.py @@ -64,10 +64,7 @@ _LOGGER = logging.getLogger(__name__) def _is_tracked(mac: str, current_devices: ValuesView) -> bool: """Check if device is already tracked.""" - for tracked in current_devices: - if mac in tracked: - return True - return False + return any(mac in tracked for tracked in current_devices) def device_filter_out_from_trackers( diff --git a/homeassistant/components/homematicip_cloud/climate.py b/homeassistant/components/homematicip_cloud/climate.py index 9c79e1a0c55..c4304284892 100644 --- a/homeassistant/components/homematicip_cloud/climate.py +++ b/homeassistant/components/homematicip_cloud/climate.py @@ -305,11 +305,7 @@ class HomematicipHeatingGroup(HomematicipGenericEntity, ClimateEntity): @property def _has_switch(self) -> bool: """Return, if a switch is in the hmip heating group.""" - for device in self._device.devices: - if isinstance(device, Switch): - return True - - return False + return any(isinstance(device, Switch) for device in self._device.devices) @property def _has_radiator_thermostat(self) -> bool: diff --git a/homeassistant/components/mqtt/event.py b/homeassistant/components/mqtt/event.py index 2a639e55352..c72791f3284 100644 --- a/homeassistant/components/mqtt/event.py +++ b/homeassistant/components/mqtt/event.py @@ -141,8 +141,7 @@ class MqttEvent(MqttEntity, EventEntity): if ( not payload or payload is PayloadSentinel.DEFAULT - or payload == PAYLOAD_NONE - or payload == PAYLOAD_EMPTY_JSON + or payload in (PAYLOAD_NONE, PAYLOAD_EMPTY_JSON) ): _LOGGER.debug( "Ignoring empty payload '%s' after rendering for topic %s", diff --git a/homeassistant/components/philips_js/binary_sensor.py b/homeassistant/components/philips_js/binary_sensor.py index d1004cfd00b..a21d1416192 100644 --- a/homeassistant/components/philips_js/binary_sensor.py +++ b/homeassistant/components/philips_js/binary_sensor.py @@ -64,10 +64,7 @@ def _check_for_recording_entry(api: PhilipsTV, entry: str, value: str) -> bool: """Return True if at least one specified value is available within entry of list.""" if api.recordings_list is None: return False - for rec in api.recordings_list["recordings"]: - if rec.get(entry) == value: - return True - return False + return any(rec.get(entry) == value for rec in api.recordings_list["recordings"]) class PhilipsTVBinarySensorEntityRecordingType(PhilipsJsEntity, BinarySensorEntity): diff --git a/homeassistant/helpers/intent.py b/homeassistant/helpers/intent.py index 82385f0cda8..71f9fd90b92 100644 --- a/homeassistant/helpers/intent.py +++ b/homeassistant/helpers/intent.py @@ -197,11 +197,7 @@ def _has_name( if (entity is None) or (not entity.aliases): return False - for alias in entity.aliases: - if name == alias.casefold(): - return True - - return False + return any(name == alias.casefold() for alias in entity.aliases) def _find_area( diff --git a/pylint/plugins/hass_enforce_type_hints.py b/pylint/plugins/hass_enforce_type_hints.py index 21438ab48ff..678cbb7a22a 100644 --- a/pylint/plugins/hass_enforce_type_hints.py +++ b/pylint/plugins/hass_enforce_type_hints.py @@ -3050,10 +3050,7 @@ def _get_named_annotation( def _has_valid_annotations( annotations: list[nodes.NodeNG | None], ) -> bool: - for annotation in annotations: - if annotation is not None: - return True - return False + return any(annotation is not None for annotation in annotations) def _get_module_platform(module_name: str) -> str | None: diff --git a/pyproject.toml b/pyproject.toml index 5d2573ab0ab..6d4bfb9e4e2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -627,8 +627,16 @@ select = [ "S604", # call-with-shell-equals-true "S608", # hardcoded-sql-expression "S609", # unix-command-wildcard-injection + "SIM101", # Multiple isinstance calls for {name}, merge into a single call + "SIM103", # Return the condition {condition} directly "SIM105", # Use contextlib.suppress({exception}) instead of try-except-pass + "SIM107", # Don't use return in try-except and finally + "SIM109", # Use {replacement} instead of multiple equality comparisons + "SIM110", # Use {replacement} instead of for loop + "SIM112", # Use capitalized environment variable {expected} instead of {actual} + "SIM113", # Use enumerate() for index variable {index} in for loop "SIM114", # Combine if branches using logical or operator + "SIM116", # Use a dictionary instead of consecutive if statements "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} diff --git a/script/hassfest/config_schema.py b/script/hassfest/config_schema.py index 9f652691887..0bc1cbebd93 100644 --- a/script/hassfest/config_schema.py +++ b/script/hassfest/config_schema.py @@ -33,10 +33,7 @@ def _has_function( module: ast.Module, _type: ast.AsyncFunctionDef | ast.FunctionDef, name: str ) -> bool: """Test if the module defines a function.""" - for item in module.body: - if type(item) == _type and item.name == name: - return True - return False + return any(type(item) == _type and item.name == name for item in module.body) def _has_import(module: ast.Module, name: str) -> bool: diff --git a/tests/components/litterrobot/test_select.py b/tests/components/litterrobot/test_select.py index 76bba67f932..48ec1bb06a5 100644 --- a/tests/components/litterrobot/test_select.py +++ b/tests/components/litterrobot/test_select.py @@ -37,9 +37,7 @@ async def test_wait_time_select( data = {ATTR_ENTITY_ID: SELECT_ENTITY_ID} - count = 0 - for wait_time in LitterRobot3.VALID_WAIT_TIMES: - count += 1 + for count, wait_time in enumerate(LitterRobot3.VALID_WAIT_TIMES): data[ATTR_OPTION] = wait_time await hass.services.async_call( @@ -49,7 +47,7 @@ async def test_wait_time_select( blocking=True, ) - assert mock_account.robots[0].set_wait_time.call_count == count + assert mock_account.robots[0].set_wait_time.call_count == count + 1 async def test_invalid_wait_time_select(hass: HomeAssistant, mock_account) -> None: @@ -91,9 +89,8 @@ async def test_panel_brightness_select( robot: LitterRobot4 = mock_account_with_litterrobot_4.robots[0] robot.set_panel_brightness = AsyncMock(return_value=True) - count = 0 - for option in select.attributes[ATTR_OPTIONS]: - count += 1 + + for count, option in enumerate(select.attributes[ATTR_OPTIONS]): data[ATTR_OPTION] = option await hass.services.async_call( @@ -103,4 +100,4 @@ async def test_panel_brightness_select( blocking=True, ) - assert robot.set_panel_brightness.call_count == count + assert robot.set_panel_brightness.call_count == count + 1 diff --git a/tests/components/litterrobot/test_switch.py b/tests/components/litterrobot/test_switch.py index feaaa1217b8..d81c02bee49 100644 --- a/tests/components/litterrobot/test_switch.py +++ b/tests/components/litterrobot/test_switch.py @@ -58,13 +58,11 @@ async def test_on_off_commands( data = {ATTR_ENTITY_ID: entity_id} - count = 0 services = ((SERVICE_TURN_ON, STATE_ON, "1"), (SERVICE_TURN_OFF, STATE_OFF, "0")) - for service, new_state, new_value in services: - count += 1 + for count, (service, new_state, new_value) in enumerate(services): await hass.services.async_call(PLATFORM_DOMAIN, service, data, blocking=True) robot._update_data({updated_field: new_value}, partial=True) - assert getattr(robot, robot_command).call_count == count + assert getattr(robot, robot_command).call_count == count + 1 assert (state := hass.states.get(entity_id)) assert state.state == new_state diff --git a/tests/components/media_extractor/test_init.py b/tests/components/media_extractor/test_init.py index 4a979b6aec6..35570e3257d 100644 --- a/tests/components/media_extractor/test_init.py +++ b/tests/components/media_extractor/test_init.py @@ -233,14 +233,13 @@ async def test_cookiefile_detection( if not os.path.exists(cookies_dir): os.makedirs(cookies_dir) - f = open(cookies_file, "w+", encoding="utf-8") - f.write( - """# Netscape HTTP Cookie File + with open(cookies_file, "w+", encoding="utf-8") as f: + f.write( + """# Netscape HTTP Cookie File - .youtube.com TRUE / TRUE 1701708706 GPS 1 - """ - ) - f.close() + .youtube.com TRUE / TRUE 1701708706 GPS 1 + """ + ) await hass.services.async_call( DOMAIN, diff --git a/tests/components/mqtt/test_common.py b/tests/components/mqtt/test_common.py index a25a670fa34..8c023848fc4 100644 --- a/tests/components/mqtt/test_common.py +++ b/tests/components/mqtt/test_common.py @@ -1710,10 +1710,8 @@ async def help_test_publishing_with_custom_encoding( # setup test entities using discovery mqtt_mock = await mqtt_mock_entry() - item: int = 0 - for component_config in setup_config: + for item, component_config in enumerate(setup_config): conf = json.dumps(component_config) - item += 1 async_fire_mqtt_message( hass, f"homeassistant/{domain}/component_{item}/config", conf ) diff --git a/tests/components/template/test_fan.py b/tests/components/template/test_fan.py index 11a0afbaf33..1c4e0d20170 100644 --- a/tests/components/template/test_fan.py +++ b/tests/components/template/test_fan.py @@ -404,17 +404,17 @@ async def test_invalid_availability_template_keeps_component_available( async def test_on_off(hass: HomeAssistant, calls) -> None: """Test turn on and turn off.""" await _register_components(hass) - expected_calls = 0 - for func, state, action in [ - (common.async_turn_on, STATE_ON, "turn_on"), - (common.async_turn_off, STATE_OFF, "turn_off"), - ]: + for expected_calls, (func, state, action) in enumerate( + [ + (common.async_turn_on, STATE_ON, "turn_on"), + (common.async_turn_off, STATE_OFF, "turn_off"), + ] + ): await func(hass, _TEST_FAN) assert hass.states.get(_STATE_INPUT_BOOLEAN).state == state _verify(hass, state, 0, None, None, None) - expected_calls += 1 - assert len(calls) == expected_calls + assert len(calls) == expected_calls + 1 assert calls[-1].data["action"] == action assert calls[-1].data["caller"] == _TEST_FAN diff --git a/tests/components/zha/test_cluster_handlers.py b/tests/components/zha/test_cluster_handlers.py index 30d892fb436..fd8ca31fe9f 100644 --- a/tests/components/zha/test_cluster_handlers.py +++ b/tests/components/zha/test_cluster_handlers.py @@ -380,7 +380,7 @@ def test_cluster_handler_registry() -> None: assert cluster_id in all_quirk_ids assert isinstance(cluster_handler_classes, dict) for quirk_id, cluster_handler in cluster_handler_classes.items(): - assert isinstance(quirk_id, NoneType) or isinstance(quirk_id, str) + assert isinstance(quirk_id, (NoneType, str)) assert issubclass(cluster_handler, cluster_handlers.ClusterHandler) assert quirk_id in all_quirk_ids[cluster_id] diff --git a/tests/components/zha/test_device_trigger.py b/tests/components/zha/test_device_trigger.py index 2698866ebaa..f9141795ef1 100644 --- a/tests/components/zha/test_device_trigger.py +++ b/tests/components/zha/test_device_trigger.py @@ -72,10 +72,7 @@ def _same_lists(list_a, list_b): if len(list_a) != len(list_b): return False - for item in list_a: - if item not in list_b: - return False - return True + return all(item in list_b for item in list_a) @pytest.fixture diff --git a/tests/components/zha/test_discover.py b/tests/components/zha/test_discover.py index 760f6da5337..cdf8e137690 100644 --- a/tests/components/zha/test_discover.py +++ b/tests/components/zha/test_discover.py @@ -70,10 +70,7 @@ IGNORE_SUFFIXES = [ def contains_ignored_suffix(unique_id: str) -> bool: """Return true if the unique_id ends with an ignored suffix.""" - for suffix in IGNORE_SUFFIXES: - if suffix.lower() in unique_id.lower(): - return True - return False + return any(suffix.lower() in unique_id.lower() for suffix in IGNORE_SUFFIXES) @patch( diff --git a/tests/helpers/test_check_config.py b/tests/helpers/test_check_config.py index fdb61505d5e..09ecaac6638 100644 --- a/tests/helpers/test_check_config.py +++ b/tests/helpers/test_check_config.py @@ -43,11 +43,9 @@ BAD_CORE_CONFIG = "homeassistant:\n unit_system: bad\n\n\n" def log_ha_config(conf): """Log the returned config.""" - cnt = 0 _LOGGER.debug("CONFIG - %s lines - %s errors", len(conf), len(conf.errors)) - for key, val in conf.items(): - _LOGGER.debug("#%s - %s: %s", cnt, key, val) - cnt += 1 + for cnt, (key, val) in enumerate(conf.items()): + _LOGGER.debug("#%s - %s: %s", cnt + 1, key, val) for cnt, err in enumerate(conf.errors): _LOGGER.debug("error[%s] = %s", cnt, err)