Repository navigation
Description
Summary
Home Assistant runs mypy over its ZHA integration, but against an untyped zha. The library ships no PEP 561 py.typed marker, so mypy treats everything imported from zha as Any, and none of the integration's ~50 imports from it are checked. This task tracks three steps: ship the marker in zha (and zha-quirks), make the HA integration clean against the real types, then add ZHA to HA's .strict-typing. That is also what HA's strict-typing quality-scale rule checks: the integration in .strict-typing, and a py.typed (or a types-* stub package) for every direct requirement, here zha and zha-quirks.
zigpy already ships py.typed. It was added in zigpy/zigpy#1260, removed again in zigpy/zigpy#1267 (its annotations "aren't enough to work with Home Assistant"), and has been back since zigpy/zigpy#1740. The ZHA integration is the only HA integration that imports the zigpy libraries.
The marker can't simply be added to zha today. With it, HA's mypy reports 195 errors in the ZHA integration, mostly from one HA-side typing shortcut, so the next zha bump would fail HA's CI. The order in the plan avoids that.
Measurements
Measured on HA Core dev at 445744e80c0 with HA's own mypy.ini and mypy 2.4.1, against zha 2.4.3 (what HA pins; zha dev has no changes under zha/ since that tag). Counts are errors in homeassistant/components/zha only; no other HA module gains errors from the marker.
| zha | HA as is | HA with ZHA in strict mode |
|---|---|---|
| 2.4.3 as released (no marker) | 0 | 70 |
2.4.3 + py.typed |
195 | 260 |
2.4.3 + py.typed, HA prototype from step 4 applied |
43 | 56 |
| 2.4.3 as released, HA prototype applied | 0 | 59 |
zha with steps 1 and 2 + py.typed, HA prototype applied |
28 | 40 |
The last row removes the 19 zha-side errors that steps 1 and 2 fix (18 without the strict flags). It also exposes 3 HA-side ones the missing methods hid: cover's tilt_position passed as Any | None, and the raw str state that cover and lock pass to restore_external_state_attributes.
- HA checks the types zha exports with HA's own flags (Python 3.14, its strict settings). The per-module suppressions in zha's
pyproject.tomldon't apply there. - A
py.typedinzhaquirkschanges nothing in HA's results (HA imports it in two places). zhaitself is checked with most strict flags, with 182 errors suppressed through those per-module overrides (50no-untyped-def, 49no-any-return, 28no-untyped-call, …). Full--strictwould report 258. That debt doesn't block the marker, but each unannotated public function is an untyped call for HA in strict mode.- A wheel built here with current setuptools already contains
zha/py.typedwithout any config. zha's build requirement issetuptools>=61.0.0, though, and older setuptools doesn't include the file automatically. The marker PR therefore needs an explicit[tool.setuptools.package-data]entry, like zigpy's.
Why the marker breaks HA's mypy
HA's EntityData.entity is typed PlatformEntity | GroupEntity, so ZHAEntity._zha_state is a BaseEntityState. Every platform then reads its own fields from that. The result is 70 × "BaseEntityState" has no attribute … plus 47 × each of Item "PlatformEntity" … and Item "GroupEntity" of "PlatformEntity | GroupEntity" has no attribute …. zha already narrows state per platform (Cover.state -> CoverEntityState, Light.state -> LightState, …), so this is fixed on the HA side.
A prototype makes EntityData and ZHAEntity generic over the zha entity and state types, with every platform parameterised by its narrowest shared zha base (BaseLight / LightState, BaseCover / CoverEntityState, …). It also fixes HA-only annotation slips. Size: 23 files, +180 / −69.
- Type-neutral against the released zha: with the untyped zha, the prototype adds no mypy error (fourth row of the table).
- Behaviour-neutral as far as checked:
EntityDatabecomesfrozen=True, which makes it covariant. Nothing in HA or its tests assigns to its fields or relies on its hashing. The other changes are imports, generic bases, twocast()calls and@override. - Not tested yet: HA's ZHA tests have not been run against it.
Of the 56 errors left with that prototype, 19 are gaps in zha's annotations, 1 is in zigpy, and 36 need HA-side fixes. The zha gaps, all unchanged on zha dev:
- Methods missing on the base classes HA calls through:
BaseCover: the tilt methods andrestore_external_state_attributes(onlyCoverdefines them).BaseLock: the user-code methods andrestore_external_state_attributes(onlyDoorLock).BaseSelectEntity:restore_external_state_attributes.BaseEntity:async_update(bothPlatformEntityandGroupEntitydefine one).BaseDevice:get_diagnostics_json(both device classes implement it).
- State types:
SelectStatehas nooptions; onlyEnumSelectStatedoes, although every select exposesoptions.BaseCoverandBaseBinarySensordon't narrowstate; only their subclasses do. This is not among the 19 errors: the prototype'scastcovers it.
- Field types wider or narrower than the values:
BaseEntityState.availableisbool | None, but is onlyNonein the abstract placeholder.- The light's
min_mireds/max_miredsareint | None, but are neverNone. BaseEntityState.fallback_nameis typedstrbut receives astr | None.
ZigbeeDevice.issue_cluster_command(manufacturer: int | None = None)doesn't admit theUNDEFINEDthat HA passes.write_zigbee_attributealready takesint | UndefinedType | None = UNDEFINED.
The zigpy one: BackupManager only defines __getitem__, so HA's for backup in application_controller.backups works at runtime, but type checkers don't see it as iterable. It needs an __iter__.
A bug the types surfaced
ZigbeeDevice.issue_cluster_command never passes its manufacturer argument on to zigpy. Both send paths call the cluster command without it, and the value only appears in the debug log. A manufacturer code given to the zha.issue_zigbee_cluster_command action is therefore silently dropped, while set_zigbee_cluster_attribute and the group command do pass it on.
zigpy then picks the code itself, in this order:
- the command definition's explicit manufacturer code;
- its manufacturer-specific flag (none when false; the cluster's
manufacturer_id_overrideor the device's manufacturer ID when true); - for clusters 0xFC00–0xFFFF, the override or the device's manufacturer ID.
That hides the bug for most manufacturer clusters. It matters when the caller's code differs from what zigpy picks, or for a command on a standard cluster whose definition carries no manufacturer information.
The fix must pass the value on only when a code was given. Quirk command() overrides default manufacturer to None, and one of the Tuya ones branches on it, so an UNDEFINED must not reach them. HA's two manufacturer is None branches can then go: the action's auto-fill and the group command's "Missing manufacturer" log. Neither has run since HA started defaulting manufacturer to ZIGPY_UNDEFINED (the "Bump ZHA to 0.0.88" change).
Plan
-
zha — annotation fixes (
code quality). Declare the shared methods on the platform base classes and fix the state and field types listed above. No runtime change for the existing entity classes; the diagnostics snapshots are regenerated becauseoptionsmoves within the select state (key order only). Branch: zigpy-bot/typing-base-class-contracts. -
zha — pass the manufacturer code on (
bugfix). Makeissue_cluster_commandacceptUNDEFINEDin its signature, likewrite_zigbee_attribute, and pass the code on as described in the bug section, with a test. Branch: zigpy-bot/forward-cluster-command-manufacturer. -
zigpy —
BackupManager.__iter__. One method. It reaches HA only through a zigpy release, zha's dependency bump and HA's zha bump. Branch: zigpy-bot/backup-manager-iter. -
HA Core — make the ZHA integration clean against a typed zha. Generic
EntityData/ZHAEntityfrom the prototype, then the remaining HA-side fixes. The prototype is split into two branches on the TheJulianJES/core fork: zigpy-bot/zha-annotation-fixes (HA-only annotation fixes, no runtime change) and, stacked on it, zigpy-bot/zha-typed-entity-data (the generics;EntityDatabecomes a frozen dataclass). Remaining HA-side fixes, for example:Nonehandling aroundget_device;- the siren services passing HA's
Platformenum where zha's is expected; websocket_apidefining its ownClusterBindinginstead of using zha's;DATA_ZHAbecoming aHassKey;- the dead
manufacturerbranches.
It is type-neutral against the released zha, so it can merge before step 5. HA's CI can't confirm it is clean against a typed zha until step 5 ships, though: the errors from steps 1–3 remain until those are released and bumped, and new ones can land in between. HA Core takes no bot commits, so a maintainer opens this one.
-
zha — ship
py.typedwith thepackage-dataentry. Release it after steps 1–3 are in a zha release and step 4 has merged. The HA bump PR for that release is the real check, and fixes whatever is left. Branch: zigpy-bot/py-typed, stacked on step 1. -
zha-quirks — ship
py.typed. Needed only for HA's quality-scale rule; measured no effect on HA's mypy, so it can happen any time. The quirks repo's own mypy debt is separate and not a prerequisite. Branch: zigpy-bot/py-typed. -
HA Core — add
homeassistant.components.zha.*to.strict-typing. The prototype shows 13 more errors with the strict flags. Three of them go with steps 1 and 4 (fallback_nameand the two deadmanufacturerbranches); the same PR fixes the rest, mostlyAnyreturns. Once HA also bumps to zha and zha-quirks releases with the marker, the integration meets thestrict-typingrule (if it gets aquality_scale.yaml).
Other zigpy libraries
zigpy already ships py.typed. Strict typing and markers for the radio libraries and zha-quirks are tracked in #87, with prepared branches for each.
Related: zigpy/zha#931 (gateway typing against BaseDevice, one of the suppressed zha errors) and zigpy/zha#999 (orphaned type parameters).
Requesting the steps
Each zigpy-side step has a pushed branch, reviewed until clean, and a drafted PR text. A maintainer can have the bot open the PRs from this thread. Steps 1–3 and 6 can start now:
@zigpy-review-bot open the PRs for steps 1 and 2 of this issue in zigpy/zha from their branches, and the PR for step 3 in zigpy/zigpy.
@zigpy-review-bot open the PR for step 6 of this issue in zigpy/zha-device-handlers from its branch.
Step 5 can be opened now as a draft stacked on step 1, but only merged once steps 1–3 are in a release and step 4 has merged in HA Core:
@zigpy-review-bot open the PR for step 5 of this issue in zigpy/zha as a draft, stacked on step 1.
Steps 4 and 7 are HA Core PRs, which a maintainer opens: step 4 from the fork branches above, step 7 once the rest has landed.
How this was measured
- HA Core worktree at dev 445744e80c0, fresh Python 3.14 venv:
uv pip install -e . mypy==2.4.1 pydantic==2.14.3 zha==2.4.3 zha-quirks==2.4.1. Thenmypy homeassistant/components/zhawith HA'smypy.ini. Errors outsidecomponents/zhacome from packages not installed in that venv; they were the same with and without the marker. - Marker: zha 2.4.3 with
zha/py.typedadded, built withuv build --wheeland installed with--no-deps --reinstall.zha/py.typedis in the wheel with and without apackage-dataentry. - Strict: a
[mypy-homeassistant.components.zha.*]section with the eight flags hassfest writes for.strict-typingentries, appended tomypy.ini. - zha's own debt: zha dev 2da1a5b5 through
tools.regenerate_mypy_ignores.run_mypy()(its flags without the per-module overrides), and once more with--strict. - Libraries: the released versions zha 2.4.3 pins, checked from source with zha's base flags and with
--strict(--ignore-missing-imports --follow-imports=silent). zigpy with-p zigpyand default flags. - The manufacturer drop was checked in
zha/zigbee/device.py(the twogetattr(cluster, commands[command].name)(…)calls) and with a probe against a fake cluster: the command received only the arguments, withoutmanufacturer.
Activity