From f2cca205c1cee6d2337357cc76eb27f933070dd7 Mon Sep 17 00:00:00 2001 From: Jey Burrows <175012+jeyrb@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:14:01 +0000 Subject: [PATCH] feat: strict type checking with Home Assistant's settings, Platinum quality scale pyproject.toml now applies the strict mypy settings Home Assistant core gives the integrations in its .strict-typing to custom_components.supernotify, the equivalent a custom integration can have. Fixing the 54 errors: type parameters for every generic, typed returns where values came back as Any, wider types where defensive checks handle unexpected input, and the cached raw image path and reprocess option declared on Notification. type: ignore comments go from 15 to 3, each with its error code. With action-setup and the Gold docs rules done, every rule is done or exempt, so the manifest, README badge and quality_scale.yaml say Platinum. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + README.md | 2 +- custom_components/supernotify/__init__.py | 6 ++-- custom_components/supernotify/archive.py | 3 +- .../supernotify/binary_sensor.py | 9 ++++-- custom_components/supernotify/common.py | 2 +- custom_components/supernotify/hass_api.py | 32 +++++++++---------- custom_components/supernotify/manifest.json | 2 +- custom_components/supernotify/media_grab.py | 12 ++++--- custom_components/supernotify/model.py | 10 +++--- custom_components/supernotify/notification.py | 22 +++++++------ .../supernotify/quality_scale.yaml | 15 ++++++--- custom_components/supernotify/repairs.py | 3 +- custom_components/supernotify/schema.py | 4 +-- custom_components/supernotify/snoozer.py | 2 +- custom_components/supernotify/target.py | 3 +- .../supernotify/transports/gotify.py | 6 ++-- .../supernotify/transports/mobile_push.py | 5 +-- .../supernotify/transports/ntfy.py | 2 +- .../supernotify/transports/telegram.py | 8 ++--- docs/developer/design/design_principles.md | 2 +- pyproject.toml | 23 +++++++++++++ 22 files changed, 109 insertions(+), 65 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bdab8280a7..e4eead6046 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ - *Actions*: the `supernotify.*` actions, such as `supernotify.notify` and `supernotify.snooze`, are there from when Home Assistant starts, rather than only once Supernotify has loaded, so an automation using them no longer fails to validate while it starts, or if it failed to start. Until it has loaded, they say so with an error. Home Assistant's [action-setup](https://contributors.home-assistant.io/core/quality-scale/action-setup/) rule, needed for its Bronze quality level ## 📝 Other changes +- *Quality*: Supernotify now meets every rule of Home Assistant's [Integration Quality Scale](https://contributors.home-assistant.io/core/quality-scale/) up to Platinum, self-assessed, see [quality_scale.yaml](https://github.com/rhizomatics/supernotify/blob/main/custom_components/supernotify/quality_scale.yaml). The last were the actions being there from startup, the entities and troubleshooting documentation, and strict type checking with Home Assistant's own settings - *Documentation*: a page on [Supernotify's entities](https://supernotify.rhizomatics.org.uk/latest/usage/entities/), what each does and when it updates, and [common problems](https://supernotify.rhizomatics.org.uk/latest/help/troubleshooting/#common-problems) on the Troubleshooting page, each with its cause and fix # v2.19.1 diff --git a/README.md b/README.md index 67ae91d9b3..8153be0b94 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ # Supernotify - Unified Notifications for Home Assistant -[![Rhizomatics Open Source](https://img.shields.io/badge/rhizomatics%20open%20source-lightseagreen)](https://github.com/rhizomatics) [![managed by hq](https://raw.githubusercontent.com/rhizomatics/hq/main/assets/badge-managed-by-hq.svg)](https://hq.rhizomatics.org.uk/) [![Home Assistant Marketplace][marketplacebadge]][marketplace] [![Quality scale: Silver (self-assessed)](https://img.shields.io/badge/quality%20scale-silver%20(self--assessed)-a8a9ad)](https://github.com/rhizomatics/supernotify/blob/main/custom_components/supernotify/quality_scale.yaml) +[![Rhizomatics Open Source](https://img.shields.io/badge/rhizomatics%20open%20source-lightseagreen)](https://github.com/rhizomatics) [![managed by hq](https://raw.githubusercontent.com/rhizomatics/hq/main/assets/badge-managed-by-hq.svg)](https://hq.rhizomatics.org.uk/) [![Home Assistant Marketplace][marketplacebadge]][marketplace] [![Quality scale: Platinum (self-assessed)](https://img.shields.io/badge/quality%20scale-platinum%20(self--assessed)-e5e4e2)](https://github.com/rhizomatics/supernotify/blob/main/custom_components/supernotify/quality_scale.yaml) ![py3.14](https://img.shields.io/badge/Python-3.14-blue) [![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/rhizomatics/supernotify) diff --git a/custom_components/supernotify/__init__.py b/custom_components/supernotify/__init__.py index 4690709337..519fff052d 100644 --- a/custom_components/supernotify/__init__.py +++ b/custom_components/supernotify/__init__.py @@ -143,7 +143,9 @@ def _entry_full_config(hass: HomeAssistant, entry: SupernotifyConfigEntry) -> Co } -def async_add_recipient_subentries(hass: HomeAssistant, entry: SupernotifyConfigEntry, recipients: list[dict]) -> None: +def async_add_recipient_subentries( + hass: HomeAssistant, entry: SupernotifyConfigEntry, recipients: list[dict[str, Any]] +) -> None: """Add a recipient subentry for each of these validated recipients that has none yet, keyed by recipient_key(), and titled by its alias, else its person's name""" from types import MappingProxyType @@ -274,7 +276,7 @@ def _async_import_yaml_recipients(hass: HomeAssistant, entry: SupernotifyConfigE from .const import CONF_RECIPIENTS from .repairs import async_check_yaml_recipients - recipients: list[dict] = hass.data.get(DOMAIN, {}).get(KEY_YAML_CONFIG, {}).get(CONF_RECIPIENTS) or [] + recipients: list[dict[str, Any]] = hass.data.get(DOMAIN, {}).get(KEY_YAML_CONFIG, {}).get(CONF_RECIPIENTS) or [] async_add_recipient_subentries(hass, entry, recipients) async_check_yaml_recipients(hass, bool(recipients)) diff --git a/custom_components/supernotify/archive.py b/custom_components/supernotify/archive.py index c2e0e2c095..93ec3adac6 100644 --- a/custom_components/supernotify/archive.py +++ b/custom_components/supernotify/archive.py @@ -385,7 +385,8 @@ async def read_entry(self, notification_id: str) -> dict[str, Any] | None: # the whole id, as base_filename() puts it after the time, not just some part of it if entry.name.endswith(f"_{notification_id}.json"): async with aiofiles.open(entry.path, mode="r") as fh: - return json.loads(await fh.read()) + entry_data: dict[str, Any] = json.loads(await fh.read()) + return entry_data except Exception as exc: _LOGGER.warning("SUPERNOTIFY Unable to read archive entry %s: %s", notification_id, exc) return None diff --git a/custom_components/supernotify/binary_sensor.py b/custom_components/supernotify/binary_sensor.py index 8558212ba3..f60addeb04 100644 --- a/custom_components/supernotify/binary_sensor.py +++ b/custom_components/supernotify/binary_sensor.py @@ -182,7 +182,8 @@ def is_on(self) -> bool | None: @property def extra_state_attributes(self) -> dict[str, object]: - return sanitize(self._scenario.attributes(include_condition=False)) + attributes: dict[str, object] = sanitize(self._scenario.attributes(include_condition=False)) + return attributes async def async_added_to_hass(self) -> None: await super().async_added_to_hass() @@ -260,7 +261,8 @@ def is_on(self) -> bool: @property def extra_state_attributes(self) -> dict[str, object]: - return sanitize(self._recipient.attributes()) + attributes: dict[str, object] = sanitize(self._recipient.attributes()) + return attributes async def async_added_to_hass(self) -> None: await super().async_added_to_hass() @@ -297,7 +299,8 @@ def is_on(self) -> bool: @property def extra_state_attributes(self) -> dict[str, object]: - return sanitize(self._model.attributes()) + attributes: dict[str, object] = sanitize(self._model.attributes()) + return attributes async def async_added_to_hass(self) -> None: await super().async_added_to_hass() diff --git a/custom_components/supernotify/common.py b/custom_components/supernotify/common.py index 25c26921e7..c2d2f93ab9 100644 --- a/custom_components/supernotify/common.py +++ b/custom_components/supernotify/common.py @@ -38,7 +38,7 @@ def safe_get(probably_a_dict: dict[Any, Any] | None, key: Any, default: Any = No return probably_a_dict.get(key, default) -def safe_extend(target: list[Any], extension: list[Any] | tuple[Any] | Any) -> list[Any]: # ruff: ignore[any-type] +def safe_extend(target: list[Any] | Any, extension: list[Any] | tuple[Any] | Any) -> list[Any]: # ruff: ignore[any-type] if target is None: target = [] elif not isinstance(target, list): diff --git a/custom_components/supernotify/hass_api.py b/custom_components/supernotify/hass_api.py index 26cd52ac98..9a537f1463 100644 --- a/custom_components/supernotify/hass_api.py +++ b/custom_components/supernotify/hass_api.py @@ -281,7 +281,7 @@ def disconnect(self) -> None: _LOGGER.error("SUPERNOTIFY Failed to unsubscribe: %s", e) _LOGGER.debug("SUPERNOTIFY Disconnection complete") - def subscribe_event(self, event: EventType[Any] | str, callback: Callable) -> None: + def subscribe_event(self, event: EventType[Any] | str, callback: Callable[..., Any]) -> None: """Listen for an event on Home Assistant's bus, until disconnect()""" self.unsubscribes.append(self._hass.bus.async_listen(event, callback)) @@ -291,7 +291,9 @@ def subscribe_mobile_app_changes(self, on_change: Callable[[], Awaitable[None]], Re-pairing or renaming a phone changes its notify action, and HA registers that action a little after the device itself, so both kinds of change are debounced into one call """ - debouncer: Debouncer = Debouncer(self._hass, _LOGGER, cooldown=cooldown, immediate=False, function=on_change) + debouncer: Debouncer[Awaitable[None]] = Debouncer( + self._hass, _LOGGER, cooldown=cooldown, immediate=False, function=on_change + ) @callback def on_device(event: Event) -> None: @@ -317,15 +319,15 @@ def on_service(event: Event) -> None: self.subscribe_event(EVENT_SERVICE_REMOVED, on_service) self.unsubscribes.append(debouncer.async_cancel) - def subscribe_state(self, entity_ids: str | Iterable[str], callback: Callable) -> None: + def subscribe_state(self, entity_ids: str | Iterable[str], callback: Callable[..., Any]) -> None: """Listen for state changes of these entities, until disconnect()""" self.unsubscribes.append(async_track_state_change_event(self._hass, entity_ids, callback)) - def subscribe_time(self, hour: int, minute: int, second: int, callback: Callable) -> None: + def subscribe_time(self, hour: int, minute: int, second: int, callback: Callable[..., Any]) -> None: """Call back daily at this time of day, until disconnect()""" self.unsubscribes.append(async_track_time_change(self._hass, callback, hour=hour, minute=minute, second=second)) - def subscribe_interval(self, seconds: int, callback: Callable) -> None: + def subscribe_interval(self, seconds: int, callback: Callable[..., Any]) -> None: """Call back every so many seconds, until disconnect()""" self.unsubscribes.append(async_track_time_interval(self._hass, callback, timedelta(seconds=seconds))) @@ -492,7 +494,7 @@ def entity_ids_named(self, name: str) -> list[str]: return [s.entity_id for s in self._hass.states.async_all() if wanted in self.entity_spoken_names(s.entity_id)] def entity_ids_for_platform( - self, domain: str, platform: str, device_model_select: str | list[str] | dict | SelectionRule | None = None + self, domain: str, platform: str, device_model_select: str | list[str] | dict[str, Any] | SelectionRule | None = None ) -> list[str]: """entity_ids in `domain` (e.g. "notify") registered by a specific integration. @@ -565,7 +567,7 @@ def _store(self, key: str, version: int) -> Store[Any]: self._stores[key] = Store(self._hass, version, key) return self._stores[key] - def create_job(self, func: Callable, *args: Any) -> asyncio.Future[Any]: + def create_job(self, func: Callable[..., Any], *args: Any) -> asyncio.Future[Any]: """Wrap a blocking function call in a HomeAssistant awaitable job""" return self._hass.async_add_executor_job(func, *args) @@ -657,7 +659,7 @@ def coerce_schema(self, domain: str, service: str, data: ConfigType) -> ConfigTy extra=vol.REMOVE_EXTRA if service_schema.extra == vol.PREVENT_EXTRA else service_schema.extra, required=service_schema.required, ) - cleaned = coercing_schema(data) + cleaned: dict[str, Any] = coercing_schema(data) else: return data if cleaned != data: @@ -1071,7 +1073,7 @@ def device_config_info(self, device: DeviceEntry) -> dict[str, str | None]: results: dict[str, str | None] = {ATTR_OS_NAME: None, ATTR_OS_VERSION: None, CONF_USER_ID: None, ATTR_APP_VERSION: None} try: # HA 2026.8+ restricts devices to a single config entry - config_entry_ids: Iterable[str] = (device.config_entry_id,) # type: ignore[attr-defined] + config_entry_ids: Iterable[str] = (device.config_entry_id,) except AttributeError: # pre-2026.8: config_entry_id doesn't exist yet, fall back to deprecated plural set config_entry_ids = device.config_entries @@ -1105,7 +1107,7 @@ def discover_devices( # 2026.8 HA and prior all_ha_devices = dev_reg.devices.values() else: - all_ha_devices = dev_reg.devices # type: ignore[assignment] + all_ha_devices = dev_reg.devices for dev in all_ha_devices: all_devs += 1 @@ -1160,9 +1162,7 @@ def discover_devices( # HomeKit has triples for identifiers, other domains may behave similarly _LOGGER.debug("SUPERNOTIFY Ignoring device %s id: %s", dev.name, identifier) else: - _LOGGER.debug( # type: ignore - "SUPERNOTIFY Unexpected %s device %s without id", dev.model, dev.name - ) + _LOGGER.debug("SUPERNOTIFY Unexpected %s device %s without id", dev.model, dev.name) _LOGGER.debug("SUPERNOTIFY %s device discovery, all=%s, enabled=%s", discover_domain, all_devs, enabled_devs) _LOGGER.debug("SUPERNOTIFY %s device discovery, skipped=%s, found=%s", discover_domain, skipped_devs, found_devs) @@ -1207,7 +1207,7 @@ def find_device(self, device_id: str) -> DeviceEntry | None: if reg is None: return None try: - return reg.async_get(device_id, include_child_devices=False) # type: ignore[call-arg] + return reg.async_get(device_id, include_child_devices=False) except TypeError: # older HA return cast("DeviceEntry|None", reg.async_get(device_id)) @@ -1254,12 +1254,12 @@ async def mqtt_publish( raise -class ConditionErrorLoggingAdaptor(logging.LoggerAdapter): +class ConditionErrorLoggingAdaptor(logging.LoggerAdapter[logging.Logger]): def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self.condition_errors: list[ConditionError] = [] - def capture(self, args: list | tuple | None) -> None: + def capture(self, args: list[Any] | tuple[Any, ...] | None) -> None: if args and isinstance(args, list | tuple): for arg in args: if isinstance(arg, ConditionErrorContainer): diff --git a/custom_components/supernotify/manifest.json b/custom_components/supernotify/manifest.json index c96c2e9912..f4aea866a3 100644 --- a/custom_components/supernotify/manifest.json +++ b/custom_components/supernotify/manifest.json @@ -43,7 +43,7 @@ "integration_type": "service", "iot_class": "calculated", "issue_tracker": "https://github.com/rhizomatics/supernotify/issues", - "quality_scale": "silver", + "quality_scale": "platinum", "requirements": [ "beautifulsoup4>=4.13.3", "aiofiles>=24.1.0" diff --git a/custom_components/supernotify/media_grab.py b/custom_components/supernotify/media_grab.py index c34fa6e091..a911051ee3 100644 --- a/custom_components/supernotify/media_grab.py +++ b/custom_components/supernotify/media_grab.py @@ -344,7 +344,8 @@ def select_avail_camera( for alt_cam in alt_cams: if camera_available(hass_api, alt_cam): _LOGGER.info("SUPERNOTIFY Selecting available camera %s rather than %s", alt_cam[CONF_CAMERA], camera_entity_id) - return alt_cam[CONF_CAMERA] + selected: str = alt_cam[CONF_CAMERA] + return selected if avail_camera_entity_id is None: _LOGGER.warning("SUPERNOTIFY %s not available, finding best alternative available", camera_entity_id) @@ -356,7 +357,8 @@ def select_avail_camera( _LOGGER.info( "SUPERNOTIFY Selecting alt camera %s with no known entity for %s", alt_cam[CONF_CAMERA], camera_entity_id ) - return alt_cam[CONF_CAMERA] + alt_selected: str = alt_cam[CONF_CAMERA] + return alt_selected return None @@ -401,7 +403,7 @@ async def snap_notification_image( subsequent calls return the cached path immediately. """ if getattr(notification, "_raw_image_path", None) is not None: - return notification._raw_image_path # type: ignore[attr-defined] + return notification._raw_image_path if notification.media.get(ATTR_MEDIA_SNAPSHOT_PATH) is not None: return Path(notification.media[ATTR_MEDIA_SNAPSHOT_PATH]) @@ -433,7 +435,7 @@ async def snap_notification_image( failures=reasons, ) if raw_path is not None: - notification._raw_image_reprocess = source.get(MEDIA_OPTION_REPROCESS) # type: ignore[attr-defined] # ty: ignore[missing-attribute] + notification._raw_image_reprocess = source.get(MEDIA_OPTION_REPROCESS) if notification.media.get(ATTR_MEDIA_SNAPSHOT_URL) != url: # deliveries that pass the URL on, rather than fetch it, get the one that worked notification.media[ATTR_MEDIA_SNAPSHOT_URL] = url @@ -506,7 +508,7 @@ async def snap_notification_image( if raw_path is None: _LOGGER.warning("SUPERNOTIFY No media available to attach (%s,%s)", sources, camera_entity_id) - notification._raw_image_path = raw_path # type: ignore[attr-defined] + notification._raw_image_path = raw_path return raw_path diff --git a/custom_components/supernotify/model.py b/custom_components/supernotify/model.py index 24d73fdddd..e3df26cacb 100644 --- a/custom_components/supernotify/model.py +++ b/custom_components/supernotify/model.py @@ -144,7 +144,7 @@ def as_dict(self, **_kwargs: Any) -> dict[str, Any]: class SelectionRule: - def __init__(self, config: str | list[str] | dict | SelectionRule | None) -> None: + def __init__(self, config: str | list[str] | dict[str, Any] | SelectionRule | None) -> None: # local import: see TransportConfig.__init__ for why this can't be module-level from .options import SELECT_EXCLUDE, SELECT_INCLUDE @@ -199,7 +199,7 @@ class DataFilter: include and exclude can be combined; any non-reserved key adds a sub-filter. """ - def __init__(self, config: str | list[str] | dict | None) -> None: + def __init__(self, config: str | list[str] | dict[str, Any] | None) -> None: self._include: list[str] | None = None self._exclude: list[str] | None = None self._sub: dict[str, DataFilter] = {} @@ -212,7 +212,7 @@ def __init__(self, config: str | list[str] | dict | None) -> None: else: self._init_from_dict(config) - def _init_from_dict(self, config: dict) -> None: + def _init_from_dict(self, config: dict[str, Any]) -> None: # local import: see TransportConfig.__init__ for why this can't be module-level from .options import SELECT_EXCLUDE, SELECT_INCLUDE @@ -247,7 +247,7 @@ def _init_from_dict(self, config: dict) -> None: self._sub[k] = DataFilter(v) @staticmethod - def _parse_exclude_tree(tree: dict) -> tuple[list[str], dict[str, DataFilter]]: + def _parse_exclude_tree(tree: dict[str, Any]) -> tuple[list[str], dict[str, DataFilter]]: excludes: list[str] = [] subs: dict[str, DataFilter] = {} for k, v in tree.items(): @@ -258,7 +258,7 @@ def _parse_exclude_tree(tree: dict) -> tuple[list[str], dict[str, DataFilter]]: return excludes, subs @staticmethod - def _exclude_tree_to_filter(tree: dict) -> DataFilter: + def _exclude_tree_to_filter(tree: dict[str, Any]) -> DataFilter: df = DataFilter(None) excludes, subs = DataFilter._parse_exclude_tree(tree) df._exclude = excludes or None diff --git a/custom_components/supernotify/notification.py b/custom_components/supernotify/notification.py index d7d6a24c6c..906aa1c15c 100644 --- a/custom_components/supernotify/notification.py +++ b/custom_components/supernotify/notification.py @@ -74,6 +74,7 @@ from .target import TargetEntityCategory if TYPE_CHECKING: + from anyio import Path from homeassistant.core import Context as HAContext from .context import Context @@ -262,7 +263,9 @@ def __init__( self.enabled_scenarios: dict[str, Scenario] = {} self.selected_scenario_names: list[str] = [] self._suppression_reason: SuppressionReason | None = None - self._raw_image_path: Any = None + self._raw_image_path: Path | None = None + # the `reprocess` given with the snapshot URL that gave the image, if any + self._raw_image_reprocess: str | None = None self._delivery_error: list[str] | None = None self.condition_variables: ConditionVariables self.unknown_names: dict[str, list[str]] = self._unknown_names() @@ -787,7 +790,7 @@ async def deliver(self) -> bool: immediate_deliveries[delivery_name] = details # Start image grab immediately so PTZ runs while immediate deliveries execute - image_task: asyncio.Task | None = None + image_task: asyncio.Task[Any] | None = None if deferred_deliveries: image_task = asyncio.create_task(_snap_notification_image(self, self.context, ha_context=self.ha_context)) @@ -1062,8 +1065,7 @@ def record_result( self.error_count += envelope.error_count self.deliveries.setdefault(delivery.name, {}) if envelope.delivered: - self.deliveries[delivery.name].setdefault(EnvelopeOutcome.SUCCESS, []) - self.deliveries[delivery.name][EnvelopeOutcome.SUCCESS].append(envelope) # type: ignore + cast("list[Envelope]", self.deliveries[delivery.name].setdefault(EnvelopeOutcome.SUCCESS, [])).append(envelope) envelope.record_recipient_notifications(self._recorded_person_ids) else: if suppression_reason: @@ -1073,12 +1075,14 @@ def record_result( if suppression_reason == SuppressionReason.DUPE: self.dupe = True if envelope.error_count: - self.deliveries[delivery.name].setdefault(EnvelopeOutcome.ERROR, []) - self.deliveries[delivery.name][EnvelopeOutcome.ERROR].append(envelope) # type: ignore + cast("list[Envelope]", self.deliveries[delivery.name].setdefault(EnvelopeOutcome.ERROR, [])).append( + envelope + ) self.failed += 1 else: - self.deliveries[delivery.name].setdefault(EnvelopeOutcome.SUPPRESSED, []) - self.deliveries[delivery.name][EnvelopeOutcome.SUPPRESSED].append(envelope) # type: ignore + cast("list[Envelope]", self.deliveries[delivery.name].setdefault(EnvelopeOutcome.SUPPRESSED, [])).append( + envelope + ) self.suppressed += 1 if not envelope: @@ -1271,7 +1275,7 @@ def base_filename(self) -> str: """ArchiveableObject implementation""" return f"{self.created.isoformat()[:16].replace(':', '-')}_{self.id}" - def delivery_data(self, delivery: Delivery) -> dict[str, Any]: + def delivery_data(self, delivery: Delivery | None) -> dict[str, Any]: if delivery is None: return {} delivery_override: DeliveryCustomization | None = self.delivery_overrides.get(delivery.name) diff --git a/custom_components/supernotify/quality_scale.yaml b/custom_components/supernotify/quality_scale.yaml index e1bc9bf393..65ff7974bd 100644 --- a/custom_components/supernotify/quality_scale.yaml +++ b/custom_components/supernotify/quality_scale.yaml @@ -1,6 +1,7 @@ --- # Quality Scale tracking for Supernotify integration -# Updated: 2026-11-02 (previous updates: 2026-08-06, 2025-12-19) +# Updated: 2026-11-25 (previous updates: 2026-11-02, 2026-08-06, 2025-12-19) +# 2026-11-25: action-setup, the Gold docs rules and strict-typing done, so every rule is done or exempt # Rule set verified against https://contributors.home-assistant.io/core/quality-scale/rules/#checklist # (HA 2026.10.4; 54 rules). 2026-11-02: no rules added, removed, renamed or moved since 2026-08-06; # statuses re-checked against the code (2026-Q4 architecture review). @@ -394,8 +395,12 @@ rules: Properly uses async_get_clientsession(hass) in media_grab.py. strict-typing: - status: todo + status: done comment: | - py.typed present and mypy passes, but not in strict mode (no strict settings in - pyproject.toml), and 14 "# type: ignore" remain (hass_api.py, notification.py, - media_grab.py, target.py, snoozer.py, scenario.py, llm.py). + A custom integration can't be listed in core's .strict-typing, so pyproject.toml [tool.mypy] + applies the same strict settings core gives the integrations listed there (no_implicit_reexport + aside, which core doesn't use either) to custom_components.supernotify, and mypy passes with + them, as does ty. py.typed is present, and entry setup is typed against SupernotifyConfigEntry. + Three "# type: ignore" remain, each with its error code: two for differences between the + Home Assistant versions supported (llm.py, scenario.py), and one for a defensive branch + (snoozer.py). diff --git a/custom_components/supernotify/repairs.py b/custom_components/supernotify/repairs.py index 7157bd57d7..3bd3ec8daa 100644 --- a/custom_components/supernotify/repairs.py +++ b/custom_components/supernotify/repairs.py @@ -324,7 +324,8 @@ def _async_get_migration_lock(hass: HomeAssistant) -> asyncio.Lock: ConfigEntry's own setup_lock (which HA already uses internally to serialize a single entry's own setup/reload/unload) - this instead prevents two concurrent attempts at this flow (e.g. a double submit, or two admin sessions) from interleaving their file writes.""" - return hass.data.setdefault(DOMAIN, {}).setdefault("migration_lock", asyncio.Lock()) + lock: asyncio.Lock = hass.data.setdefault(DOMAIN, {}).setdefault("migration_lock", asyncio.Lock()) + return lock def _load_configuration_yaml_dict(hass: HomeAssistant) -> dict[str, Any]: diff --git a/custom_components/supernotify/schema.py b/custom_components/supernotify/schema.py index ff54a40bf3..8b07a33171 100644 --- a/custom_components/supernotify/schema.py +++ b/custom_components/supernotify/schema.py @@ -253,7 +253,7 @@ def phone(value: str) -> str: return str(value) -def validate_scenario_names(scenarios: dict) -> dict: +def validate_scenario_names(scenarios: dict[str, Any]) -> dict[str, Any]: """Validate that scenario names are not reserved.""" for name in scenarios: if name in RESERVED_SCENARIO_NAMES: @@ -375,7 +375,7 @@ def validate_scenario_names(scenarios: dict) -> dict: }) -def _migrate_condition(config: dict) -> dict: +def _migrate_condition(config: dict[str, Any]) -> dict[str, Any]: """Migrate deprecated 'condition' key to 'conditions'.""" if CONF_CONDITION in config: if CONF_CONDITIONS not in config: diff --git a/custom_components/supernotify/snoozer.py b/custom_components/supernotify/snoozer.py index 2db3a564f6..b7c0557183 100644 --- a/custom_components/supernotify/snoozer.py +++ b/custom_components/supernotify/snoozer.py @@ -311,7 +311,7 @@ def register_snooze( if to_del: self._persist() else: - _LOGGER.warning( # type: ignore + _LOGGER.warning( # type: ignore[unreachable] "SUPERNOTIFY Invalid mobile cmd %s (target_type: %s, target: %s, recipient_type: %s)", cmd, target_type, diff --git a/custom_components/supernotify/target.py b/custom_components/supernotify/target.py index fea869f083..f26dbfb077 100644 --- a/custom_components/supernotify/target.py +++ b/custom_components/supernotify/target.py @@ -94,6 +94,7 @@ def __init__( | dict[str, Sequence[str]] | dict[str, list[str]] | dict[str, str | list[str]] + | object | None = None, target_data: dict[str, Any] | None = None, target_specific_data: bool = False, @@ -259,7 +260,7 @@ def is_notify_entity(cls, target: str) -> bool: @classmethod def is_email(cls, target: str) -> bool: try: - return vol.Email()(target) is not None # type: ignore[call-arg] + return vol.Email()(target) is not None except vol.Invalid: return False diff --git a/custom_components/supernotify/transports/gotify.py b/custom_components/supernotify/transports/gotify.py index 2804620ed4..338f01ed7a 100644 --- a/custom_components/supernotify/transports/gotify.py +++ b/custom_components/supernotify/transports/gotify.py @@ -74,11 +74,11 @@ def _build_extras( image_url: str | None, markdown: bool, intent_url: str | None, -) -> dict | None: +) -> dict[str, Any] | None: """Build Gotify extras dict. Returns None if no extras are needed.""" - extras: dict = {} + extras: dict[str, Any] = {} - client_notification: dict = {} + client_notification: dict[str, Any] = {} if click_url: client_notification["click"] = {"url": click_url} if image_url: diff --git a/custom_components/supernotify/transports/mobile_push.py b/custom_components/supernotify/transports/mobile_push.py index b288648e07..9b21bc07d6 100644 --- a/custom_components/supernotify/transports/mobile_push.py +++ b/custom_components/supernotify/transports/mobile_push.py @@ -307,8 +307,9 @@ async def action_title(self, url: str, retry_timeout: int = 900) -> str | None: # wrap heavy bs4 parsing in a job to avoid blocking the event loop html = await self.context.hass_api.create_job(BeautifulSoup, body, "html.parser") if html.title and html.title.string: - self.action_titles[url] = html.title.string - return html.title.string + title: str = html.title.string + self.action_titles[url] = title + return title except Exception as e: _LOGGER.warning("SUPERNOTIFY Failed to retrieve url title at %s: %s", url, e) self.action_title_failures[url] = time.time() diff --git a/custom_components/supernotify/transports/ntfy.py b/custom_components/supernotify/transports/ntfy.py index e5e830abf3..e95c9d464c 100644 --- a/custom_components/supernotify/transports/ntfy.py +++ b/custom_components/supernotify/transports/ntfy.py @@ -91,7 +91,7 @@ def _parse_delay(delay: str) -> str: return delay -def _validate_actions(actions: list) -> list: +def _validate_actions(actions: list[Any]) -> list[Any]: """Validate ntfy action buttons, dropping malformed entries with a warning.""" valid = [] for i, a in enumerate(actions): diff --git a/custom_components/supernotify/transports/telegram.py b/custom_components/supernotify/transports/telegram.py index 82904426df..7c9b2084ce 100644 --- a/custom_components/supernotify/transports/telegram.py +++ b/custom_components/supernotify/transports/telegram.py @@ -108,7 +108,7 @@ def _fit(text: str, limit: int, parse_mode: str) -> tuple[str, str]: return text[:limit], "plain_text" -def _normalise_inline_keyboard(keyboard: list) -> list: +def _normalise_inline_keyboard(keyboard: Any) -> list[Any]: # ruff: ignore[any-type] """Normalise a user-supplied inline keyboard to the HA telegram_bot shape. Accepts: @@ -123,11 +123,11 @@ def _normalise_inline_keyboard(keyboard: list) -> list: """ if not isinstance(keyboard, list): return [] - out: list = [] + out: list[Any] = [] for row in keyboard: if not isinstance(row, list): continue - out_row: list = [] + out_row: list[Any] = [] for btn in row: if isinstance(btn, list) and len(btn) >= 2: # Already in HA shape: [label, callback_or_url] @@ -142,7 +142,7 @@ def _normalise_inline_keyboard(keyboard: list) -> list: return out -def _build_inline_keyboard(actions: list) -> list: +def _build_inline_keyboard(actions: list[Any]) -> list[Any]: """Convert SuperNotify actions to HA telegram_bot inline keyboard format. SuperNotify actions are dicts with keys "title" (button label) diff --git a/docs/developer/design/design_principles.md b/docs/developer/design/design_principles.md index 3ff5e2a1ff..8b726241eb 100644 --- a/docs/developer/design/design_principles.md +++ b/docs/developer/design/design_principles.md @@ -56,7 +56,7 @@ which Principle 7 applies here. Make Supernotify more accessible to more users, including non-technical ones who will never use YAML. Supernotify should itself make HomeAssistant more accessible, for example by simplifying mobile push setup. - Move towards Platinum quality scale level and maintain this quality + Keep the Platinum quality scale level, self-assessed in `quality_scale.yaml`, with each new rule met as it is added Note the tension with Principle #6 diff --git a/pyproject.toml b/pyproject.toml index 744aaab5e7..f83baf110a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -248,6 +248,29 @@ addopts = [ "no:respx", ] +[tool.mypy] +# Home Assistant core's strict settings, as for an integration listed in its .strict-typing +# (Quality Scale strict-typing), which leave out mypy --strict's no_implicit_reexport +local_partial_types = true +strict_equality = true +warn_redundant_casts = true +warn_unused_configs = true +warn_unused_ignores = true +enable_error_code = ["ignore-without-code", "redundant-self", "truthy-iterable"] +extra_checks = true + +[[tool.mypy.overrides]] +module = ["custom_components.supernotify.*"] +check_untyped_defs = true +disallow_incomplete_defs = true +disallow_subclassing_any = true +disallow_untyped_calls = true +disallow_untyped_decorators = true +disallow_untyped_defs = true +disallow_any_generics = true +warn_return_any = true +warn_unreachable = true + [[tool.mypy.overrides]] module = ["pytest_homeassistant_custom_component.*"] follow_untyped_imports = true