Skip to content

Commit

Permalink
Add ruff rules PIE790, PIE794, PIE807, PIE810 (home-assistant#113617)
Browse files Browse the repository at this point in the history
  • Loading branch information
autinerd authored Mar 16, 2024
1 parent cbe2a58 commit 0b9c9af
Show file tree
Hide file tree
Showing 25 changed files with 29 additions and 47 deletions.
1 change: 0 additions & 1 deletion homeassistant/components/alexa/intent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
10 changes: 2 additions & 8 deletions homeassistant/components/buienradar/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -774,13 +774,7 @@ def _load_data(self, data): # noqa: C901
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"):
Expand All @@ -793,7 +787,7 @@ def _load_data(self, data): # noqa: C901
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:
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/cast/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
6 changes: 1 addition & 5 deletions homeassistant/components/cast/media_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -685,11 +685,7 @@ async def async_play_media(
"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(
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/discovergy/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/elkm1/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/google_domains/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/iaqualink/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def __init__(self, dev: AqualinkSwitch) -> None:
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"
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/isy994/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ async def async_step_dhcp(
) -> 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}"
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/kodi/notify.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 "
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/no_ip/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/upnp/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/uptimerobot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/uptimerobot/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ async def _validate_input(
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
Expand Down
1 change: 0 additions & 1 deletion homeassistant/components/webhook/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,6 @@ async def _handle(self, request: Request, webhook_id: str) -> Response:
head = _handle
post = _handle
put = _handle
get = _handle


@websocket_api.websocket_command(
Expand Down
4 changes: 1 addition & 3 deletions homeassistant/components/xiaomi_aqara/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,9 +158,7 @@ async def async_step_zeroconf(
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"
Expand Down
6 changes: 2 additions & 4 deletions homeassistant/components/xiaomi_miio/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
6 changes: 2 additions & 4 deletions homeassistant/components/xiaomi_miio/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
5 changes: 5 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion tests/components/homekit/test_homekit.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}
Expand Down
6 changes: 3 additions & 3 deletions tests/components/recorder/db_schema_16.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
Expand Down Expand Up @@ -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"),
Expand Down Expand Up @@ -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"),
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 0 additions & 2 deletions tests/components/twitch/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,6 @@ def __await__(self):

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
Expand Down Expand Up @@ -157,7 +156,6 @@ async def set_user_authentication(
validate: bool = True,
) -> None:
"""Set user authentication."""
pass

async def get_followed_channels(
self, user_id: str, broadcaster_id: str | None = None
Expand Down
1 change: 0 additions & 1 deletion tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down

0 comments on commit 0b9c9af

Please sign in to comment.