From 0b9c9aff62b2945ea3bc3420efd6d89662fad882 Mon Sep 17 00:00:00 2001 From: Sid <27780930+autinerd@users.noreply.github.com> Date: Sat, 16 Mar 2024 22:04:58 +0100 Subject: [PATCH] Add ruff rules PIE790, PIE794, PIE807, PIE810 (#113617) --- homeassistant/components/alexa/intent.py | 1 - homeassistant/components/buienradar/sensor.py | 10 ++-------- homeassistant/components/cast/helpers.py | 2 +- homeassistant/components/cast/media_player.py | 6 +----- homeassistant/components/discovergy/sensor.py | 2 +- homeassistant/components/elkm1/config_flow.py | 2 +- homeassistant/components/google_domains/__init__.py | 2 +- homeassistant/components/iaqualink/switch.py | 2 +- homeassistant/components/isy994/config_flow.py | 2 +- homeassistant/components/kodi/notify.py | 2 +- homeassistant/components/no_ip/__init__.py | 2 +- homeassistant/components/upnp/device.py | 2 +- homeassistant/components/uptimerobot/__init__.py | 2 +- homeassistant/components/uptimerobot/config_flow.py | 2 +- homeassistant/components/webhook/__init__.py | 1 - homeassistant/components/xiaomi_aqara/config_flow.py | 4 +--- homeassistant/components/xiaomi_miio/__init__.py | 6 ++---- homeassistant/components/xiaomi_miio/sensor.py | 6 ++---- pyproject.toml | 5 +++++ tests/components/homekit/test_homekit.py | 2 +- tests/components/recorder/db_schema_16.py | 6 +++--- .../recorder/db_schema_23_with_newer_columns.py | 2 +- tests/components/twitch/__init__.py | 2 -- tests/test_core.py | 1 - .../config_flow.py | 2 -- 25 files changed, 29 insertions(+), 47 deletions(-) diff --git a/homeassistant/components/alexa/intent.py b/homeassistant/components/alexa/intent.py index 03c6ac640e3..8d266e4a634 100644 --- a/homeassistant/components/alexa/intent.py +++ b/homeassistant/components/alexa/intent.py @@ -50,7 +50,6 @@ async def async_setup_intents(hass: HomeAssistant) -> None: Right now this module does not expose any, but the intent component breaks without it. """ - pass # pylint: disable=unnecessary-pass class UnknownRequest(HomeAssistantError): diff --git a/homeassistant/components/buienradar/sensor.py b/homeassistant/components/buienradar/sensor.py index d0847c111fb..fb15aa49001 100644 --- a/homeassistant/components/buienradar/sensor.py +++ b/homeassistant/components/buienradar/sensor.py @@ -774,13 +774,7 @@ class BrSensor(SensorEntity): self._measured = data.get(MEASURED) sensor_type = self.entity_description.key - if ( - sensor_type.endswith("_1d") - or sensor_type.endswith("_2d") - or sensor_type.endswith("_3d") - or sensor_type.endswith("_4d") - or sensor_type.endswith("_5d") - ): + if sensor_type.endswith(("_1d", "_2d", "_3d", "_4d", "_5d")): # update forecasting sensors: fcday = 0 if sensor_type.endswith("_2d"): @@ -793,7 +787,7 @@ class BrSensor(SensorEntity): fcday = 4 # update weather symbol & status text - if sensor_type.startswith(SYMBOL) or sensor_type.startswith(CONDITION): + if sensor_type.startswith((SYMBOL, CONDITION)): try: condition = data.get(FORECAST)[fcday].get(CONDITION) except IndexError: diff --git a/homeassistant/components/cast/helpers.py b/homeassistant/components/cast/helpers.py index eff6bf18e8b..2d4e1a9dbfa 100644 --- a/homeassistant/components/cast/helpers.py +++ b/homeassistant/components/cast/helpers.py @@ -360,7 +360,7 @@ async def parse_pls(hass, url): async def parse_playlist(hass, url): """Parse an m3u or pls playlist.""" - if url.endswith(".m3u") or url.endswith(".m3u8"): + if url.endswith((".m3u", ".m3u8")): playlist = await parse_m3u(hass, url) else: playlist = await parse_pls(hass, url) diff --git a/homeassistant/components/cast/media_player.py b/homeassistant/components/cast/media_player.py index 941b2e0675b..037e154eb96 100644 --- a/homeassistant/components/cast/media_player.py +++ b/homeassistant/components/cast/media_player.py @@ -685,11 +685,7 @@ class CastMediaPlayerEntity(CastDevice, MediaPlayerEntity): "hlsVideoSegmentFormat": "fmp4", }, } - elif ( - media_id.endswith(".m3u") - or media_id.endswith(".m3u8") - or media_id.endswith(".pls") - ): + elif media_id.endswith((".m3u", ".m3u8", ".pls")): try: playlist = await parse_playlist(self.hass, media_id) _LOGGER.debug( diff --git a/homeassistant/components/discovergy/sensor.py b/homeassistant/components/discovergy/sensor.py index cb9f8c3bf1d..0a820917821 100644 --- a/homeassistant/components/discovergy/sensor.py +++ b/homeassistant/components/discovergy/sensor.py @@ -43,7 +43,7 @@ class DiscovergySensorEntityDescription(SensorEntityDescription): value_fn: Callable[[Reading, str, int], datetime | float | None] = field( default=_get_and_scale ) - alternative_keys: list[str] = field(default_factory=lambda: []) + alternative_keys: list[str] = field(default_factory=list) scale: int = field(default_factory=lambda: 1000) diff --git a/homeassistant/components/elkm1/config_flow.py b/homeassistant/components/elkm1/config_flow.py index 6e4874f7366..5991c502ef6 100644 --- a/homeassistant/components/elkm1/config_flow.py +++ b/homeassistant/components/elkm1/config_flow.py @@ -78,7 +78,7 @@ async def validate_input(data: dict[str, str], mac: str | None) -> dict[str, str prefix = data[CONF_PREFIX] url = _make_url_from_data(data) - requires_password = url.startswith("elks://") or url.startswith("elksv1_2") + requires_password = url.startswith(("elks://", "elksv1_2")) if requires_password and (not userid or not password): raise InvalidAuth diff --git a/homeassistant/components/google_domains/__init__.py b/homeassistant/components/google_domains/__init__.py index d6537c5e135..a4dcef62964 100644 --- a/homeassistant/components/google_domains/__init__.py +++ b/homeassistant/components/google_domains/__init__.py @@ -73,7 +73,7 @@ async def _update_google_domains(hass, session, domain, user, password, timeout) resp = await session.get(url, params=params) body = await resp.text() - if body.startswith("good") or body.startswith("nochg"): + if body.startswith(("good", "nochg")): return True _LOGGER.warning("Updating Google Domains failed: %s => %s", domain, body) diff --git a/homeassistant/components/iaqualink/switch.py b/homeassistant/components/iaqualink/switch.py index 05eed0725e3..e681879855b 100644 --- a/homeassistant/components/iaqualink/switch.py +++ b/homeassistant/components/iaqualink/switch.py @@ -40,7 +40,7 @@ class HassAqualinkSwitch(AqualinkEntity, SwitchEntity): self._attr_icon = "mdi:robot-vacuum" elif name == "Waterfall" or name.endswith("Dscnt"): self._attr_icon = "mdi:fountain" - elif name.endswith("Pump") or name.endswith("Blower"): + elif name.endswith(("Pump", "Blower")): self._attr_icon = "mdi:fan" if name.endswith("Heater"): self._attr_icon = "mdi:radiator" diff --git a/homeassistant/components/isy994/config_flow.py b/homeassistant/components/isy994/config_flow.py index c66e8af4022..639e591746d 100644 --- a/homeassistant/components/isy994/config_flow.py +++ b/homeassistant/components/isy994/config_flow.py @@ -213,7 +213,7 @@ class Isy994ConfigFlow(ConfigFlow, domain=DOMAIN): ) -> ConfigFlowResult: """Handle a discovered ISY/IoX device via dhcp.""" friendly_name = discovery_info.hostname - if friendly_name.startswith("polisy") or friendly_name.startswith("eisy"): + if friendly_name.startswith(("polisy", "eisy")): url = f"http://{discovery_info.ip}:8080" else: url = f"http://{discovery_info.ip}" diff --git a/homeassistant/components/kodi/notify.py b/homeassistant/components/kodi/notify.py index 7d65321a807..05b5ff56be4 100644 --- a/homeassistant/components/kodi/notify.py +++ b/homeassistant/components/kodi/notify.py @@ -60,7 +60,7 @@ async def async_get_service( port: int = config[CONF_PORT] encryption = config.get(CONF_PROXY_SSL) - if host.startswith("http://") or host.startswith("https://"): + if host.startswith(("http://", "https://")): host = host[host.index("://") + 3 :] _LOGGER.warning( "Kodi host name should no longer contain http:// See updated " diff --git a/homeassistant/components/no_ip/__init__.py b/homeassistant/components/no_ip/__init__.py index d9084719cbd..9680464c9fa 100644 --- a/homeassistant/components/no_ip/__init__.py +++ b/homeassistant/components/no_ip/__init__.py @@ -104,7 +104,7 @@ async def _update_no_ip( resp = await session.get(url, params=params, headers=headers) body = await resp.text() - if body.startswith("good") or body.startswith("nochg"): + if body.startswith(("good", "nochg")): _LOGGER.debug("Updating NO-IP success: %s", domain) return True diff --git a/homeassistant/components/upnp/device.py b/homeassistant/components/upnp/device.py index 9e8aaea198b..04d8b3414bd 100644 --- a/homeassistant/components/upnp/device.py +++ b/homeassistant/components/upnp/device.py @@ -38,7 +38,7 @@ def get_preferred_location(locations: set[str]) -> str: """Get the preferred location (an IPv4 location) from a set of locations.""" # Prefer IPv4 over IPv6. for location in locations: - if location.startswith("http://[") or location.startswith("https://["): + if location.startswith(("http://[", "https://[")): continue return location diff --git a/homeassistant/components/uptimerobot/__init__.py b/homeassistant/components/uptimerobot/__init__.py index 75fa5eeabcc..afff0c8fe03 100644 --- a/homeassistant/components/uptimerobot/__init__.py +++ b/homeassistant/components/uptimerobot/__init__.py @@ -19,7 +19,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up UptimeRobot from a config entry.""" hass.data.setdefault(DOMAIN, {}) key: str = entry.data[CONF_API_KEY] - if key.startswith("ur") or key.startswith("m"): + if key.startswith(("ur", "m")): raise ConfigEntryAuthFailed( "Wrong API key type detected, use the 'main' API key" ) diff --git a/homeassistant/components/uptimerobot/config_flow.py b/homeassistant/components/uptimerobot/config_flow.py index 0afee9cfacb..feb747c6b9e 100644 --- a/homeassistant/components/uptimerobot/config_flow.py +++ b/homeassistant/components/uptimerobot/config_flow.py @@ -36,7 +36,7 @@ class UptimeRobotConfigFlow(ConfigFlow, domain=DOMAIN): errors: dict[str, str] = {} response: UptimeRobotApiResponse | UptimeRobotApiError | None = None key: str = data[CONF_API_KEY] - if key.startswith("ur") or key.startswith("m"): + if key.startswith(("ur", "m")): LOGGER.error("Wrong API key type detected, use the 'main' API key") errors["base"] = "not_main_key" return errors, None diff --git a/homeassistant/components/webhook/__init__.py b/homeassistant/components/webhook/__init__.py index 081147cc7f0..f2d1416e2c9 100644 --- a/homeassistant/components/webhook/__init__.py +++ b/homeassistant/components/webhook/__init__.py @@ -210,7 +210,6 @@ class WebhookView(HomeAssistantView): head = _handle post = _handle put = _handle - get = _handle @websocket_api.websocket_command( diff --git a/homeassistant/components/xiaomi_aqara/config_flow.py b/homeassistant/components/xiaomi_aqara/config_flow.py index ca1a5851f7e..7021b27e187 100644 --- a/homeassistant/components/xiaomi_aqara/config_flow.py +++ b/homeassistant/components/xiaomi_aqara/config_flow.py @@ -158,9 +158,7 @@ class XiaomiAqaraFlowHandler(ConfigFlow, domain=DOMAIN): return self.async_abort(reason="not_xiaomi_aqara") # Check if the discovered device is an xiaomi aqara gateway. - if not ( - name.startswith(ZEROCONF_GATEWAY) or name.startswith(ZEROCONF_ACPARTNER) - ): + if not (name.startswith((ZEROCONF_GATEWAY, ZEROCONF_ACPARTNER))): _LOGGER.debug( ( "Xiaomi device '%s' discovered with host %s, not identified as" diff --git a/homeassistant/components/xiaomi_miio/__init__.py b/homeassistant/components/xiaomi_miio/__init__.py index aa9bbe5dcc6..f21698f33c3 100644 --- a/homeassistant/components/xiaomi_miio/__init__.py +++ b/homeassistant/components/xiaomi_miio/__init__.py @@ -340,10 +340,8 @@ async def async_create_miio_device_and_coordinator( device = AirFreshA1(host, token, lazy_discover=lazy_discover) elif model == MODEL_AIRFRESH_T2017: device = AirFreshT2017(host, token, lazy_discover=lazy_discover) - elif ( - model in MODELS_VACUUM - or model.startswith(ROBOROCK_GENERIC) - or model.startswith(ROCKROBO_GENERIC) + elif model in MODELS_VACUUM or model.startswith( + (ROBOROCK_GENERIC, ROCKROBO_GENERIC) ): # TODO: add lazy_discover as argument when python-miio add support # pylint: disable=fixme device = RoborockVacuum(host, token) diff --git a/homeassistant/components/xiaomi_miio/sensor.py b/homeassistant/components/xiaomi_miio/sensor.py index a7b3ff176bd..9f70ef6bb17 100644 --- a/homeassistant/components/xiaomi_miio/sensor.py +++ b/homeassistant/components/xiaomi_miio/sensor.py @@ -831,10 +831,8 @@ async def async_setup_entry( sensors = PURIFIER_MIIO_SENSORS elif model in MODELS_PURIFIER_MIOT: sensors = PURIFIER_MIOT_SENSORS - elif ( - model in MODELS_VACUUM - or model.startswith(ROBOROCK_GENERIC) - or model.startswith(ROCKROBO_GENERIC) + elif model in MODELS_VACUUM or model.startswith( + (ROBOROCK_GENERIC, ROCKROBO_GENERIC) ): return _setup_vacuum_sensors(hass, config_entry, async_add_entities) diff --git a/pyproject.toml b/pyproject.toml index 7bc7931f18b..04aca768267 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -276,6 +276,7 @@ disable = [ "unidiomatic-typecheck", # E721 "unnecessary-direct-lambda-call", # PLC3002 "unnecessary-lambda-assignment", # PLC3001 + "unnecessary-pass", # PIE790 "unneeded-not", # SIM208 "useless-import-alias", # PLC0414 "wrong-import-order", # I001 @@ -604,6 +605,10 @@ select = [ "N815", # Variable {name} in class scope should not be mixedCase "PERF", # Perflint "PGH004", # Use specific rule codes when using noqa + "PIE790", # Unnecessary pass statement + "PIE794", # Class field is defined multiple times + "PIE807", # Prefer list/dict over useless lambda + "PIE810", # Call startswith/endswith once with a tuple "PLC0414", # Useless import alias. Import alias does not rename original package. "PLC", # pylint "PLE", # pylint diff --git a/tests/components/homekit/test_homekit.py b/tests/components/homekit/test_homekit.py index c1dcd28ce68..a6748749e1a 100644 --- a/tests/components/homekit/test_homekit.py +++ b/tests/components/homekit/test_homekit.py @@ -1297,7 +1297,7 @@ async def test_homekit_reset_accessories_not_bridged( acc_mock = MagicMock() acc_mock.entity_id = entity_id acc_mock.stop = AsyncMock() - acc_mock.to_HAP = lambda: {} + acc_mock.to_HAP = dict aid = homekit.aid_storage.get_or_allocate_aid_for_entity_id(entity_id) homekit.bridge.accessories = {aid: acc_mock} diff --git a/tests/components/recorder/db_schema_16.py b/tests/components/recorder/db_schema_16.py index 8c491b82c39..4d48400e370 100644 --- a/tests/components/recorder/db_schema_16.py +++ b/tests/components/recorder/db_schema_16.py @@ -84,7 +84,7 @@ class Events(Base): # type: ignore context_user_id = Column(String(MAX_LENGTH_EVENT_CONTEXT_ID), index=True) context_parent_id = Column(String(MAX_LENGTH_EVENT_CONTEXT_ID), index=True) - __table_args__ = ( + __table_args__ = ( # noqa: PIE794 # Used for fetching events at a specific time # see logbook Index("ix_events_event_type_time_fired", "event_type", "time_fired"), @@ -156,7 +156,7 @@ class States(Base): # type: ignore event = relationship("Events", uselist=False) old_state = relationship("States", remote_side=[state_id]) - __table_args__ = ( + __table_args__ = ( # noqa: PIE794 # Used for fetching the state of entities at a specific time # (get_states in history.py) Index("ix_states_entity_id_last_updated", "entity_id", "last_updated"), @@ -237,7 +237,7 @@ class Statistics(Base): # type: ignore state = Column(Float()) sum = Column(Float()) - __table_args__ = ( + __table_args__ = ( # noqa: PIE794 # Used for fetching statistics for a certain entity at a specific time Index("ix_statistics_statistic_id_start", "statistic_id", "start"), ) diff --git a/tests/components/recorder/db_schema_23_with_newer_columns.py b/tests/components/recorder/db_schema_23_with_newer_columns.py index f3a2dc39859..92c3f7a75ff 100644 --- a/tests/components/recorder/db_schema_23_with_newer_columns.py +++ b/tests/components/recorder/db_schema_23_with_newer_columns.py @@ -254,7 +254,7 @@ class States(Base): # type: ignore TIMESTAMP_TYPE, default=time.time ) # *** Not originally in v23, only added for recorder to startup ok last_updated = Column(DATETIME_TYPE, default=dt_util.utcnow, index=True) - last_updated_ts = Column( + last_updated_ts = Column( # noqa: PIE794 TIMESTAMP_TYPE, default=time.time, index=True ) # *** Not originally in v23, only added for recorder to startup ok created = Column(DATETIME_TYPE, default=dt_util.utcnow) diff --git a/tests/components/twitch/__init__.py b/tests/components/twitch/__init__.py index 3fa7d96337e..bb4530eacf8 100644 --- a/tests/components/twitch/__init__.py +++ b/tests/components/twitch/__init__.py @@ -123,7 +123,6 @@ class TwitchMock: async def _noop(self): """Fake function to create task.""" - pass async def get_users( self, user_ids: list[str] | None = None, logins: list[str] | None = None @@ -157,7 +156,6 @@ class TwitchMock: validate: bool = True, ) -> None: """Set user authentication.""" - pass async def get_followed_channels( self, user_id: str, broadcaster_id: str | None = None diff --git a/tests/test_core.py b/tests/test_core.py index abebcef7121..da4a87702f5 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -735,7 +735,6 @@ def test_add_job_pending_tasks_coro(hass: HomeAssistant) -> None: async def test_coro(): """Test Coro.""" - pass for _ in range(2): hass.add_job(test_coro()) diff --git a/tests/testing_config/custom_components/test_package_raises_cancelled_error_config_entry/config_flow.py b/tests/testing_config/custom_components/test_package_raises_cancelled_error_config_entry/config_flow.py index 7277bac343d..e2a7ef9281f 100644 --- a/tests/testing_config/custom_components/test_package_raises_cancelled_error_config_entry/config_flow.py +++ b/tests/testing_config/custom_components/test_package_raises_cancelled_error_config_entry/config_flow.py @@ -9,8 +9,6 @@ class MockConfigFlow( ): """Mock config flow.""" - pass - async def _async_has_devices(hass: HomeAssistant) -> bool: """Return if there are devices that can be discovered."""