Pylint plugin for Home Assistant
Custom pylint checkers for the Home Assistant codebase. These checkers enforce coding standards, quality scale compliance, and common review patterns specific to Home Assistant integrations.
This plugin extends pylint with checks that cannot be expressed as
Ruff rules because they require type
inference, cross-file analysis (reading manifest.json, quality_scale.yaml),
or AST patterns that go beyond what a linter operating on a single file
can detect.
Setup
Install the package from a Home Assistant Core checkout:
uv pip install ./packages/pylint-home-assistant
Load it using pylint --load-plugins=pylint_home_assistant or the
load-plugins setting in your Pylint configuration.
The checkers currently target Home Assistant Core's module names and repository layout. Installing the package separately does not add support for custom integration layouts.
Within Core, the init-hook in the root pyproject.toml adds
packages/pylint-home-assistant to sys.path to load the checkout's code.
Build a source distribution and wheel from the repository root:
uv build packages/pylint-home-assistant
Why not (just) Ruff?
Home Assistant uses both Ruff and pylint. Ruff handles fast, single-file linting (import sorting, formatting, common Python issues). These pylint checkers cover patterns that Ruff cannot:
- Cross-file analysis: reading
manifest.jsonto checkintegration_type, readingquality_scale.yamlto verify claims. - Type inference: resolving decorator names like
_pytest.fixtures.FixtureFunctionMarkerthrough imports. - Complex AST patterns: tracing variable assignments to API calls
(e.g., detecting that a variable assigned from
data[CONF_HOST]later flows intoasync_set_unique_id()).
Disabling checks
Always use the rule name (e.g., home-assistant-logger-period) rather than the
error code (e.g., C7401) for readability.
Single line -- add the disable comment at the end of the line:
hass.data[DOMAIN] = data # pylint: disable=home-assistant-use-runtime-data
Next line only -- if the inline comment would make the line too long,
use disable-next on the line above:
# pylint: disable-next=home-assistant-use-runtime-data
hass.data[DOMAIN] = data
Entire module -- place the disable comment at the top of the file, after the module docstring:
"""My integration setup."""
# pylint: disable=home-assistant-use-runtime-data
Automated code analysis
Every check has a code following the pylint convention:
{C,W,E,R}74{00-99}, where74is the base ID for Home Assistant.C= Convention,W= Warning,E= Error,R= Refactor.
| Code | Rule | Description |
|---|---|---|
C7401 |
home-assistant-logger-period |
Logger messages must not end with a period |
C7402 |
home-assistant-logger-capital |
Logger messages must start with a capital letter or use debug level |
C7403 |
home-assistant-relative-import |
Use relative imports within an integration |
C7404 |
home-assistant-absolute-import |
Use absolute imports for cross-integration references |
C7405 |
home-assistant-component-root-import |
Do not import from another integration's internals |
C7406 |
home-assistant-helper-namespace-import |
Use the helper namespace import pattern |
C7407 |
home-assistant-import-constant-alias |
Aliased DOMAIN import needs a descriptive alias |
C7408 |
home-assistant-import-constant-unnecessary-alias |
Unnecessary alias when importing DOMAIN within the same integration |
C7409 |
home-assistant-enforce-sorted-platforms |
PLATFORMS list must be sorted alphabetically |
C7410 |
home-assistant-enforce-greek-micro-char |
Use Greek mu (U+03BC), not ANSI micro sign (U+00B5) |
C7411 |
home-assistant-enforce-class-module |
Entity class should be in the correct platform module |
C7412 |
home-assistant-entity-description-redundant-default |
Setting an EntityDescription field to its default value is redundant |
C7414 |
home-assistant-enforce-utcnow |
Use homeassistant.util.dt.utcnow instead of datetime.now(UTC) |
C7415 |
home-assistant-domain-argument |
Domain argument in tests should be a domain constant or variable |
C7416 |
home-assistant-noqa-f401-with-all |
List re-exported names in __all__ instead of using # noqa: F401 |
C7417 |
home-assistant-init-not-first |
__init__ should be defined before other instance methods and properties |
C7425 |
home-assistant-enforce-now |
Use homeassistant.util.dt.now instead of datetime.now(<tz>) |
C7427 |
home-assistant-enforce-naive-now |
Use homeassistant.util.dt.naive_now instead of datetime.now() |
C7458 |
home-assistant-logger-const-name |
Logger in an integration's const.py should use __package__ |
C7459 |
home-assistant-placeholder-key |
Placeholder keys should be string literals, not constants such as CONF_* |
C7464 |
home-assistant-type-checking-block-position |
if TYPE_CHECKING: block should come after all module-level imports |
C7465 |
home-assistant-action-target-key |
Target keys of action calls should use TargetKey |
E7401 |
home-assistant-invalid-inheritance |
Invalid entity class inheritance chain |
E7402 |
home-assistant-argument-type |
Function argument should have the specified type hint |
E7403 |
home-assistant-return-type |
Function should have the specified return type hint |
E7404 |
home-assistant-missing-super-call |
Method must call its parent via super() |
E7405 |
home-assistant-action-swallowed-exception |
Action handler must not swallow exceptions |
E7406 |
home-assistant-exception-translation-key-missing |
Translation key not found in strings.json exceptions section |
E7407 |
home-assistant-function-async-mismatch |
Function should be a coroutine, or should not be one |
E7408 |
home-assistant-exception-translation-key-domain-mismatch |
Only one of translation_key / translation_domain is set |
E7409 |
home-assistant-mdi-icon-not-found |
MDI icon string does not exist in the Material Design Icons set |
E7410 |
home-assistant-mdi-icon-json-not-found |
MDI icon in icons.json does not exist in the Material Design Icons set |
E7418 |
home-assistant-exception-placeholder-mismatch |
Translation placeholders in code don't match strings.json |
R7401 |
home-assistant-consider-usefixtures-decorator |
Use @pytest.mark.usefixtures for unused fixtures |
R7402 |
home-assistant-unused-test-fixture-argument |
Unused test function argument should use @pytest.mark.usefixtures |
R7403 |
home-assistant-tests-redundant-usefixtures |
@pytest.mark.usefixtures redundant when pytestmark already applies it |
R7404 |
home-assistant-tests-registry-fixtures |
Use the registry fixture instead of calling <registry>.async_get(hass) directly in tests |
R7405 |
home-assistant-tests-user-flow-no-data |
User config flow init in tests must not pass data |
R7406 |
home-assistant-tests-snapshot-enable-entities |
Use the entity_registry_enabled_by_default fixture instead of enabling entities before snapshot_platform |
R7407 |
home-assistant-tests-redundant-caplog-level |
Do not set the root caplog level to DEBUG, the fixture already does |
R7408 |
home-assistant-redundant-entity-init |
Entity __init__ only forwards its arguments to super().__init__ |
W7401 |
home-assistant-deprecated-import |
Import uses a deprecated path |
W7402 |
home-assistant-async-callback-decorator |
Coroutine should not be decorated with @callback |
W7403 |
home-assistant-pytest-fixture-decorator |
Pytest fixture has invalid scope or autouse config |
W7404 |
home-assistant-async-load-fixtures |
Test fixture files should be loaded asynchronously |
W7405 |
home-assistant-use-runtime-data |
Use entry.runtime_data instead of hass.data[DOMAIN] |
W7406 |
home-assistant-unique-id-ip-based |
Unique ID should not be based on IP/hostname |
W7407 |
home-assistant-config-flow-polling-field |
Config flow should not include polling interval fields |
W7408 |
home-assistant-config-flow-name-field |
Config flow should not include name fields |
W7409 |
home-assistant-test-non-deterministic |
Test contains if/match creating non-deterministic execution |
W7410 |
home-assistant-missing-reauthentication-flow |
Config flow should implement async_step_reauth |
W7411 |
home-assistant-missing-parallel-updates |
Platform module should define PARALLEL_UPDATES |
W7412 |
home-assistant-missing-diagnostics |
Integration diagnostics module should implement a diagnostics function |
W7413 |
home-assistant-missing-config-entry-unloading |
Integration should implement async_unload_entry |
W7414 |
home-assistant-service-registered-in-setup-entry |
Services should be registered in async_setup, not async_setup_entry |
W7415 |
home-assistant-sequential-executor-jobs |
Sequential async_add_executor_job calls should be grouped |
W7416 |
home-assistant-missing-has-entity-name |
Entity class should set _attr_has_entity_name = True |
W7417 |
home-assistant-exception-not-translated |
HomeAssistantError should use translation_key/translation_domain |
W7418 |
home-assistant-tests-direct-async-setup-entry |
Tests should not call an integration's async_setup_entry directly |
W7419 |
home-assistant-exception-message-with-translation |
Don't pass a positional message when translation_key is set |
W7420 |
home-assistant-tests-direct-platform-async-setup-entry |
Tests should not call a platform's async_setup_entry directly |
W7421 |
home-assistant-tests-direct-async-migrate-entry |
Tests should not call an integration's async_migrate_entry directly |
W7422 |
home-assistant-tests-direct-async-setup |
Tests should not call an integration's async_setup directly |
W7423 |
home-assistant-missing-entity-unique-id |
Entity class does not statically guarantee a non-None unique id |
W7424 |
home-assistant-entity-unique-id-static |
Entity class sets _attr_unique_id to a static string at class level |
W7425 |
home-assistant-entity-unique-id-redundant-domain |
Entity unique ID references the DOMAIN constant or includes the integration's domain as a string-literal delimited segment |
W7426 |
home-assistant-tests-direct-async-unload-entry |
Tests should not call an integration's async_unload_entry directly |
W7427 |
home-assistant-entity-unique-id-redundant-platform |
Entity unique ID includes the entity platform name (e.g. sensor, light) as a delimited string-literal segment |
W7428 |
home-assistant-config-flow-field-not-translated |
Config flow form field missing translation in strings.json |
W7429 |
home-assistant-unnecessary-format-mac |
format_mac() is unnecessary with CONNECTION_NETWORK_MAC |
W7430 |
home-assistant-serial-port-selector-usb-dependency |
Config flow using SerialPortSelector must declare usb in dependencies |
W7431 |
home-assistant-options-flow-field-not-translated |
Options flow form field missing translation in strings.json |
W7432 |
home-assistant-subentry-flow-field-not-translated |
Subentry flow form field missing translation in strings.json |
W7433 |
home-assistant-missing-test-before-configure |
Config flow should test the connection before creating an entry |
W7434 |
home-assistant-config-flow-menu-missing-step |
async_show_menu option has no matching async_step_* method |
W7435 |
home-assistant-json-fixture |
Use a JSON fixture helper instead of parsing a loaded fixture |
W7436 |
home-assistant-light-missing-color-mode |
Light entity sets supported color modes but does not report a color_mode |
W7437 |
home-assistant-light-missing-supported-color-modes |
Light entity reports a color_mode but does not set supported color modes |
W7439 |
home-assistant-tests-coordinator-async-refresh |
Tests should advance the time instead of refreshing a coordinator directly |
W7440 |
home-assistant-tests-config-flow-unique-id |
Happy path config flow tests should assert the created entry's unique ID |
W7441 |
home-assistant-tests-config-flow-error-recovery |
Config flow tests that show an error should finish the flow afterwards |
W7442 |
home-assistant-redundant-translation-key |
translation_key only repeats the name the device_class already provides |
W7443 |
home-assistant-step_id-match-method |
Config flow should use step_id parameter value same as the method it's in |
W7445 |
home-assistant-test-flow-start-helper |
Use MockConfigEntry helpers to start reauth/reconfigure flows in tests |
W7447 |
home-assistant-coordinator-untyped-config-entry |
Coordinator should use the integration's typed config entry instead of ConfigEntry |
W7448 |
home-assistant-coordinator-redundant-config-entry |
Coordinator assigns self.config_entry that DataUpdateCoordinator.__init__ already sets |
W7449 |
home-assistant-coordinator-entity-available |
CoordinatorEntity overrides available with only coordinator.data and without super().available |
W7450 |
home-assistant-log-and-raise |
Don't log an error that is raised to Home Assistant, which already reports it |
W7452 |
home-assistant-action-registered-outside-services-module |
Actions should be registered from async_setup_services or setup_services in services.py |
W7453 |
home-assistant-invalid-setup-services |
async_setup_services / setup_services should be synchronous and only take hass |
W7454 |
home-assistant-sequential-add-entities |
Sequential async_add_entities calls should be grouped |
W7455 |
home-assistant-coordinator-entity-should-poll |
_attr_should_poll has no effect on a CoordinatorEntity |
W7457 |
home-assistant-flow-call-in-try |
Flow creates an entry, shows a form, handles the unique ID or moves on to another step inside a try block |
W7460 |
home-assistant-runtime-data-untyped-config-entry |
Config entry that sets runtime_data should use a typed config entry instead of ConfigEntry |
W7463 |
home-assistant-callback-override-missing-decorator |
Override of a @callback method should be decorated with @callback |
W7464 |
home-assistant-use-typed-config-entry |
Use the integration's typed config entry instead of ConfigEntry |
home_assistant_logger checker
Enforces consistent formatting and naming of loggers across the codebase.
C7401: home-assistant-logger-period
User-visible logger messages must not end with a period. Log messages in Home Assistant follow a convention of not using trailing punctuation.
C7402: home-assistant-logger-capital
Logger messages must start with a capital letter. Debug-level messages are exempt from this rule. If a message does not warrant capitalization, consider downgrading it to debug level.
C7458: home-assistant-logger-const-name
The logger defined in an integration's const.py must use
logging.getLogger(__package__). With __name__, log records are attributed
to homeassistant.components.<domain>.const instead of the integration.
home_assistant_imports checker
Enforces import conventions for Home Assistant integrations. Integrations should use relative imports for their own modules and follow specific patterns for cross-integration references.
C7403: home-assistant-relative-import
Use relative imports within an integration (e.g., from .const import DOMAIN
instead of from homeassistant.components.myintegration.const import DOMAIN).
W7401: home-assistant-deprecated-import
Import uses a deprecated path that has been moved or renamed.
C7404: home-assistant-absolute-import
Use absolute imports when referencing modules outside the current integration.
C7405: home-assistant-component-root-import
Do not import from another integration's internal modules. Only import from the integration's top-level public API.
C7406: home-assistant-helper-namespace-import
Use the helper namespace import pattern for helper modules.
C7407: home-assistant-import-constant-alias
Aliased DOMAIN import from another integration should use a descriptive alias.
C7408: home-assistant-import-constant-unnecessary-alias
Unnecessary alias when importing DOMAIN from within the same integration.
C7416: home-assistant-noqa-f401-with-all
In an integration module that defines __all__, re-exported names must be
listed in __all__ instead of being kept with a # noqa: F401 marker.
Imports of submodules only (e.g. from . import sensor, switch # noqa: F401,
used to preload platforms) are allowed, as are imports inside functions or
classes, which cannot be exported through __all__.
home_assistant_type_checking_block checker
Checks the position of the module-level if TYPE_CHECKING: block. Neither
ruff nor pylint flag imports after it, because both allow conditional blocks
between imports.
C7464: home-assistant-type-checking-block-position
A module-level import follows the if TYPE_CHECKING: block. Move the block
below the last import.
# Bad
if TYPE_CHECKING:
from . import MyConfigEntry
from .const import DOMAIN
# Good
from .const import DOMAIN
if TYPE_CHECKING:
from . import MyConfigEntry
home_assistant_init_first checker
Keeps integration classes readable top-down by placing the constructor directly after the class attributes.
C7417: home-assistant-init-not-first
An instance method or property is defined before __init__. Move
__init__ up so it is the first instance method of the class. Class
attributes, static methods and class methods (including __new__ and
__init_subclass__) may precede it, since those are commonly alternative
constructors or factories such as async_get_options_flow.
# Bad
class MyEntity(Entity):
_attr_has_entity_name = True
@property
def available(self) -> bool:
return self._available
def __init__(self, device: Device) -> None:
self._device = device
# Good
class MyEntity(Entity):
_attr_has_entity_name = True
def __init__(self, device: Device) -> None:
self._device = device
@property
def available(self) -> bool:
return self._available
home_assistant_enforce_type_hints checker
Enforces type hints on platform functions, config flow methods, and test functions. Checks both argument types and return types against the expected signatures defined by Home Assistant's platform interfaces.
E7402: home-assistant-argument-type
Function argument should have the specified type hint. Platform functions
like async_setup_entry have well-defined signatures that must be followed.
E7403: home-assistant-return-type
Function should have the specified return type hint.
E7407: home-assistant-function-async-mismatch
Function should be defined with async def, or with def. Home Assistant
awaits functions like async_setup_platform, and runs functions like
setup_platform in the executor, so the wrong kind fails at runtime.
R7401: home-assistant-consider-usefixtures-decorator
Test function should use @pytest.mark.usefixtures("fixture_name") instead
of accepting an unused fixture as a parameter.
home_assistant_decorator checker
Validates decorator usage on functions and fixtures.
W7402: home-assistant-async-callback-decorator
A coroutine function (async def) should not be decorated with @callback.
The @callback decorator is only for synchronous functions that should be
called from the event loop without scheduling.
W7403: home-assistant-pytest-fixture-decorator
Pytest fixture has invalid scope or autouse configuration. For example,
session-scoped fixtures in component tests should use package scope
or lower.
W7463: home-assistant-callback-override-missing-decorator
A sync method that overrides a method decorated with @callback, such as
_handle_coordinator_update of a coordinator entity or a method of an
integration's own base class, should be decorated with @callback as well.
The decorator isn't inherited, and it marks the override as running in the
event loop, where it must not do blocking I/O:
class MyEntity(CoordinatorEntity[MyCoordinator]):
@callback
def _handle_coordinator_update(self) -> None: ...
home_assistant_inheritance checker
Validates that entity platform modules only use entity classes from their
own platform (e.g., a sensor.py module should not inherit from
BinarySensorEntity).
E7401: home-assistant-invalid-inheritance
A platform module uses an entity class from a different platform. For
example, a sensor.py file should not define classes inheriting from
BinarySensorEntity.
home_assistant_enforce_super_call checker
Ensures methods call their parent implementation when required.
E7404: home-assistant-missing-super-call
Method must call its parent implementation via super(). Certain entity
methods require calling the parent to maintain correct behavior.
home_assistant_enforce_sorted_platforms checker
Ensures platform lists are maintained in alphabetical order.
C7409: home-assistant-enforce-sorted-platforms
The PLATFORMS (or _PLATFORMS) list must be sorted alphabetically. This
makes it easier to review and prevents merge conflicts.
home_assistant_enforce_greek_micro_char checker
Ensures correct Unicode character for the micro prefix.
C7410: home-assistant-enforce-greek-micro-char
Constants with a micro unit prefix (e.g., "μg/m³") must use the Greek
small letter mu (U+03BC μ), not the ANSI micro sign (U+00B5 µ). The
two characters look identical but are different Unicode code points.
home_assistant_enforce_class_module checker
Ensures entity classes are placed in the correct module.
C7411: home-assistant-enforce-class-module
A class deriving from a platform entity (e.g., SensorEntity) should be
placed in the corresponding platform module (e.g., sensor.py), not in
__init__.py or an unrelated module.
home_assistant_enforce_runtime_data checker
Enforces the modern entry.runtime_data pattern over the legacy
hass.data[DOMAIN] dictionary pattern. Only flags integrations that
have a config flow (YAML-only integrations are skipped).
W7405: home-assistant-use-runtime-data
Use entry.runtime_data instead of hass.data[DOMAIN]. The runtime_data
approach is type-safe (via ConfigEntry[T]), automatically cleaned up on
entry unload, and avoids key collisions in the shared hass.data dictionary.
See the runtime-data quality scale rule for migration guidance.
home_assistant_coordinator_config_entry checker
Checks how a DataUpdateCoordinator handles its config entry.
W7447: home-assistant-coordinator-untyped-config-entry
When an integration defines a typed config entry, such as
type MyConfigEntry = ConfigEntry[MyCoordinator], its coordinators should use
it for the config_entry class annotation and __init__ argument, so
self.config_entry.runtime_data is typed as well:
class MyCoordinator(DataUpdateCoordinator[MyData]):
config_entry: MyConfigEntry
def __init__(self, hass: HomeAssistant, config_entry: MyConfigEntry) -> None: ...
When the alias lives in __init__.py, import it in the coordinator under
if TYPE_CHECKING: to avoid a circular import, or move it to
coordinator.py.
W7448: home-assistant-coordinator-redundant-config-entry
DataUpdateCoordinator.__init__ stores the config_entry it is given, so a
coordinator that passes config_entry to super().__init__ doesn't need to
assign self.config_entry itself. To narrow its type, annotate it on the
class instead.
home_assistant_runtime_data_typed_entry checker
Checks that config entries that set runtime_data are typed.
W7460: home-assistant-runtime-data-untyped-config-entry
ConfigEntry is generic over its runtime_data. When runtime_data is set
on a config entry that is annotated as a plain ConfigEntry, that
runtime_data is Any and isn't type checked. Define a typed config entry and
use it instead:
type MyConfigEntry = ConfigEntry[MyData]
async def async_setup_entry(hass: HomeAssistant, entry: MyConfigEntry) -> bool:
entry.runtime_data = MyData(...)
home_assistant_typed_config_entry checker
Checks that integrations with a typed config entry use it.
W7464: home-assistant-use-typed-config-entry
When an integration defines a typed config entry, such as
type MyConfigEntry = ConfigEntry[MyData], it should use it everywhere it
handles its own config entry, so entry.runtime_data stays typed. Argument,
return and variable annotations that use a plain ConfigEntry, including
nested ones such as ConfigEntry | None or list[ConfigEntry], are flagged,
and so are ones that spell out ConfigEntry[MyData] instead of using the alias:
def get_device_info(entry: MyConfigEntry) -> DeviceInfo:
return entry.runtime_data.device_info
When importing the typed config entry would create a circular import, import
it under if TYPE_CHECKING:, or define it next to the class that holds the
runtime_data instead.
home_assistant_coordinator_entity_available checker
Checks available overrides on coordinator entities.
W7449: home-assistant-coordinator-entity-available
CoordinatorEntity.available returns coordinator.last_update_success, so the
entity becomes unavailable when an update fails. An override that takes its
availability only from coordinator.data keeps the entity available with the
data of the last successful update, because the coordinator keeps that data
when an update fails:
@property
def available(self) -> bool:
return super().available and self.device_id in self.coordinator.data
Properties and methods of the entity and the coordinator are followed, so
self.data or self.coordinator.get_device(...) reading coordinator.data
count as coordinator data.
Overrides with a source of their own, such as a client, a device, a websocket
or _attr_available, are not flagged. Neither are entities of a push
coordinator, one that never sets an update_interval and gets its data
through async_set_updated_data: its last_update_success doesn't show
whether the device is reachable.
home_assistant_coordinator_entity_should_poll checker
Checks for _attr_should_poll on coordinator entities.
W7455: home-assistant-coordinator-entity-should-poll
CoordinatorEntity overrides should_poll to always return False, as the
coordinator tells its entities when it has new data. _attr_should_poll is
only read by Entity.should_poll, so setting it on a coordinator entity has
no effect and can be removed.
home_assistant_log_and_raise checker
Checks for errors that are logged and then raised to Home Assistant.
W7450: home-assistant-log-and-raise
Home Assistant already reports the exceptions an integration raises to it:
config entry setup logs ConfigEntryNotReady, ConfigEntryAuthFailed and
ConfigEntryError, a coordinator logs UpdateFailed, and a failing action
returns HomeAssistantError or ServiceValidationError to the caller.
Logging the error at warning level or higher before raising it reports it
twice, and for ConfigEntryNotReady on every retry:
except MyDeviceError as err:
raise UpdateFailed(
translation_domain=DOMAIN,
translation_key="update_failed",
) from err
Put the details in the exception or log them at debug level. Exceptions that
an integration defines itself, such as a config flow's CannotConnect, are
not checked.
home_assistant_async_load_fixtures checker
Ensures test fixture files are loaded asynchronously.
W7404: home-assistant-async-load-fixtures
Test fixture files should be loaded using async I/O, not synchronous file reads. This prevents blocking the event loop during tests.
home_assistant_enforce_config_entry_unique_id_no_ip checker
Detects async_set_unique_id calls where the argument is an IP address
or hostname. IP addresses change when devices get new DHCP leases, breaking
the config entry. Uses variable tracking to catch indirect usage (e.g.,
uid = data[CONF_HOST]; await self.async_set_unique_id(uid)).
W7406: home-assistant-unique-id-ip-based
async_set_unique_id should not use an IP address or hostname. Use a
stable hardware identifier instead: a MAC address (via format_mac),
serial number, or device-provided unique ID.
See the unique-config-entry quality scale rule.
home_assistant_enforce_config_flow_no_polling checker
Detects polling interval fields in config flow schemas. Polling intervals should be fixed by the integration author, not exposed as user-configurable fields.
W7407: home-assistant-config-flow-polling-field
Config flow should not include polling interval fields like
CONF_SCAN_INTERVAL, update_interval, or refresh_interval. The
integration author determines the appropriate polling frequency based on
API rate limits, device capabilities, and data freshness needs.
See the appropriate-polling quality scale rule.
home_assistant_enforce_config_flow_no_name checker
Detects name fields (CONF_NAME, "name", CONF_DEVICE_NAME,
"device_name") in config flow schemas. Config flows should not ask
users to provide a name -- the name is automatically derived from the
device (via discovery) or set by the integration code itself.
Helper integrations (integration_type: helper in manifest.json) and
subentry flows (ConfigSubentryFlow subclasses) are excluded.
W7408: home-assistant-config-flow-name-field
Config flow should not include a name field. Users should not set names in config flows; they come automatically from the device or are set by the integration.
home_assistant_config_flow_menu_options checker
Validates that every option passed to
self.async_show_menu(menu_options=...) corresponds to an
async_step_<option> method on the flow class. Each option becomes a
next_step_id the flow manager dispatches to that method; a missing method
raises UnknownStep at runtime when the user selects the option.
Only statically resolvable forms are checked: a literal list/tuple/set of strings, or a literal dict keyed by the step ids. Dynamic forms (comprehensions, unresolved variables) and flows with an unresolvable base class are skipped to avoid false positives.
W7434: home-assistant-config-flow-menu-missing-step
A menu_options entry does not match any async_step_* method defined on
the flow class or its ancestors.
home_assistant_flow_call_in_try checker
Checks for flow calls inside a try block.
W7457: home-assistant-flow-call-in-try
A try block in a flow step should only contain the code that can raise the
errors it catches, such as the calls to the device or service. Creating the
entry, showing a form, aborting, handling the unique ID and moving on to
another step (self.async_step_*()) belong after it:
try:
info = await client.get_info()
except CannotConnect:
errors["base"] = "cannot_connect"
else:
await self.async_set_unique_id(info.serial_number)
self._abort_if_unique_id_configured()
return self.async_create_entry(title=info.name, data=user_input)
The unique ID helpers raise AbortFlow, also when called from another step,
which a broad except Exception swallows and reports as an unknown error.
try statements that catch
AbortFlow themselves are not checked.
home_assistant_unused_test_fixture_args checker
Disabled by default while existing violations are being cleaned up.
R7402: home-assistant-unused-test-fixture-argument
Test functions that receive a fixture argument but never reference it in
the function body should use @pytest.mark.usefixtures("name") instead.
This keeps the function signature clean and makes it clear the fixture is
only needed for its side effects.
This rule only applies to test_* functions, not to fixture functions.
home_assistant_domain_constant checker
Encourages using DOMAIN constants (or variables) when passing a domain to common test helpers.
String literals are allowed for cases where the constant is not imported.
Only runs on test modules.
C7415: home-assistant-domain-argument
The domain (or handler) argument to test helpers such as
async_setup_component, async_mock_service, MockConfigEntry,
hass.services.async_call, hass.services.call, and
hass.config_entries.flow.async_init should use a domain constant or variable when available.
The following are accepted:
- a
DOMAIN/domainattribute or one ending in_DOMAIN/_domain(e.g.sensor.DOMAIN), - a
DOMAIN/domainname or one ending in_DOMAIN/_domain, - a string literal (for cases where the constant is not imported),
- a subscript expression (e.g.
data["key"]).
home_assistant_tests_direct_async_setup_entry checker
Detects tests that call an integration's async_setup_entry directly.
W7418: home-assistant-tests-direct-async-setup-entry
Tests should not invoke an integration's async_setup_entry from
__init__.py directly. Instead, tests should let Home Assistant perform
the setup via await hass.config_entries.async_setup(entry.entry_id) so
that the real setup pipeline (platforms, services, listeners, unload
handlers, etc.) is exercised.
W7420: home-assistant-tests-direct-platform-async-setup-entry
Same as W7418, but for an entity platform's async_setup_entry (e.g.
homeassistant.components.<integration>.sensor.async_setup_entry).
Tests should drive setup through hass.config_entries.async_setup so
the platform is loaded via the normal Home Assistant flow.
See epic #77.
home_assistant_tests_direct_async_migrate_entry checker
Detects tests that call an integration's async_migrate_entry directly.
W7421: home-assistant-tests-direct-async-migrate-entry
Tests should not invoke an integration's async_migrate_entry from
__init__.py directly. Instead, tests should let Home Assistant perform
the setup via await hass.config_entries.async_setup(entry.entry_id) so
that the real migration pipeline (version bumps, reloads, post-migration
setup, etc.) is exercised.
See epic #78.
home_assistant_tests_direct_async_setup checker
Detects tests that call an integration's async_setup directly.
W7422: home-assistant-tests-direct-async-setup
Tests should not invoke an integration's async_setup from
__init__.py directly. Instead, tests should let Home Assistant drive
the setup through the normal pipeline:
- For integrations with config entries, add a
MockConfigEntryand callawait hass.config_entries.async_setup(entry.entry_id). - For integrations without config entries (system integrations), use
await async_setup_component(hass, DOMAIN, {...})fromhomeassistant.setup.
See epic #79.
home_assistant_tests_direct_async_unload_entry checker
Detects tests that call an integration's async_unload_entry directly.
W7426: home-assistant-tests-direct-async-unload-entry
Tests should not invoke an integration's async_unload_entry from
__init__.py directly. Instead, tests should let Home Assistant trigger
the unload via await hass.config_entries.async_unload(entry.entry_id) so
that the real unload flow (platform unloading, listener teardown,
runtime_data cleanup, etc.) is exercised.
home_assistant_tests_coordinator_async_refresh checker
Detects integration tests that refresh a coordinator directly.
W7439: home-assistant-tests-coordinator-async-refresh
Tests should not refresh a DataUpdateCoordinator by calling
async_refresh(), async_request_refresh() or _async_refresh(). Instead,
advance the time so the coordinator refreshes on its own schedule:
freezer.tick(SCAN_INTERVAL)
async_fire_time_changed(hass)
await hass.async_block_till_done(wait_background_tasks=True)
Coordinators mostly reach tests through entry.runtime_data or a fixture,
whose type cannot be inferred. So every use of these methods in
tests/components is flagged, including passing one around without calling
it, unless the receiver is known to be something other than a coordinator,
such as a mock.
home_assistant_tests_config_flow_unique_id checker
Detects config flow tests that create an entry without checking its unique ID.
W7440: home-assistant-tests-config-flow-unique-id
When the integration's config flow calls async_set_unique_id, a happy path
test in tests/components/<domain>/test_config_flow.py that asserts a
CREATE_ENTRY result should also assert the unique ID of the new entry:
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["result"].unique_id == "1234"
An assert that references unique_id or a snapshot counts as a check.
Results of options and subentry flows are ignored, as those don't set a
unique ID; results that can't be traced, such as those returned by a helper,
are checked. Tests that start an options or subentry flow are skipped, as
they run the config flow only as setup. Tests that recover from an error are
skipped too: they make a mock raise an exception through side_effect or
expect non-empty errors. Resetting a side_effect to None, replacing a
method with a function or a mock, or returning a list of values doesn't count
as an error.
home_assistant_tests_config_flow_error_recovery checker
Detects config flow tests that show an error but never prove the user can recover from it.
W7441: home-assistant-tests-config-flow-error-recovery
A config flow test that asserts a step shows an error should then fix the cause and finish the flow, so the test proves the flow recovers:
assert result["errors"] == {"base": "cannot_connect"}
mock_client.connect.side_effect = None
result = await hass.config_entries.flow.async_configure(result["flow_id"], USER_INPUT)
assert result["type"] is FlowResultType.CREATE_ENTRY
Only tests/components/<domain>/test_config_flow.py modules are checked.
Any error counts, on any field and in any flow (user, discovery, reauth,
reconfigure, options, subentry): errors == {...}, errors["base"] == ...,
"base" in errors, a bare assert result["errors"] and errors != {}, also
through a local alias such as errors = result["errors"]. A test is flagged
when, after an error assertion, it never asserts that a result has type
CREATE_ENTRY or aborted with a *_successful reason (as reauth and
reconfigure flows do); every error needs its own. A finishing assertion in a
branch that cannot run after the error, such as the else of the if that
shows the error, does not count, and neither does one after a new flow is
started with async_init: that flow is not the one that showed the error.
Helper functions from the integration's own tests are followed, both for
showing the error (such as assert_form_error(result, "cannot_connect")) and
for finishing the flow, with the arguments they are called with. A reason
taken from a test argument counts when all its pytest.mark.parametrize
values end with _successful.
See the config-flow-test-coverage quality scale rule.
home_assistant_enforce_utcnow checker
Ensures the Home Assistant helper is used to get the current UTC time.
C7414: home-assistant-enforce-utcnow
Use homeassistant.util.dt.utcnow() instead of datetime.datetime.now(UTC).
The helper is implemented as
functools.partial(datetime.datetime.now, UTC) and avoids the global
lookup of UTC on every call, while keeping the codebase consistent in
how the current UTC time is obtained.
home_assistant_enforce_now checker
Ensures the Home Assistant helper is used to get the current local time.
C7425: home-assistant-enforce-now
Use homeassistant.util.dt.now() instead of datetime.datetime.now(<tz>)
when called with a non-UTC time zone to create an aware datetime. The
helper returns an aware datetime in the given time zone (defaulting to
DEFAULT_TIME_ZONE), keeping the codebase consistent in how the current
local time is obtained. The UTC case (datetime.now(UTC)) is handled by
the home-assistant-enforce-utcnow
checker, and datetime.now() with no argument is handled by the
home-assistant-enforce-naive-now
checker.
home_assistant_enforce_naive_now checker
Ensures the Home Assistant helper is used to get the current naive local time.
C7427: home-assistant-enforce-naive-now
Use homeassistant.util.dt.naive_now() instead of datetime.datetime.now()
called without a time zone argument. The helper returns a naive datetime in
system local time, keeping the codebase consistent in how the current naive
local time is obtained and documenting that a naive datetime is intentional.
An explicit None argument (datetime.now(None) or datetime.now(tz=None))
returns a naive datetime too and is flagged. The aware cases
(datetime.now(<tz>) and datetime.now(UTC)) are handled by the
home-assistant-enforce-now and
home-assistant-enforce-utcnow
checkers.
home_assistant_entity_unique_id checker
Quality-scale-gated checker for the entity-unique-id
Bronze rule. Only fires for entity-platform modules whose
quality_scale.yaml marks entity-unique-id as done.
W7423: home-assistant-missing-entity-unique-id
Entity class does not statically guarantee a non-None unique id.
Accepted (in the class or any ancestor):
- Class body:
_attr_unique_id = <non-None value>. - A method body where every successful path executes
self._attr_unique_id = <expr>(top-level, or in both branches of anif/else). An early-return guard (if cond: return) before the assignment breaks the guarantee and is rejected; anif cond: raise ...guard is accepted since no object is constructed when the exception fires. - A
unique_idproperty/method override on the class.
A subclass that explicitly assigns _attr_unique_id = None overrides
any non-None value set by an ancestor and is flagged regardless of
what the ancestors do.
Mixin/abstract bases that are subclassed by another class in the same
module are exempted. Use
# pylint: disable=home-assistant-missing-entity-unique-id on the
class declaration as the escape hatch for dynamic patterns the static
analysis cannot follow.
W7424: home-assistant-entity-unique-id-static
Entity class sets _attr_unique_id to a literal string at class body.
Entity unique IDs are scoped per (domain, platform) across all
config entries of the integration, so a static value collides on the
second config entry of a multi-entry integration.
The rule fires when:
- the class body assigns
_attr_unique_id = "..."(or_attr_unique_id: str = "...") to a literal string, and - the integration's
manifest.jsondoes not declaresingle_config_entry: true.
Resolve by either computing the id per instance (config-entry id,
serial, MAC, etc.) or declaring the integration as
single_config_entry: true when there is genuinely only one instance.
home_assistant_entity_unique_id_format checker
Hosts format-related checks on the value an entity uses for its unique
ID (_attr_unique_id assignments and unique_id property/method
returns). Migrating unique_ids after an integration has shipped risks
disrupting existing users, so the antipatterns must be caught before
they ship. Unlike the gated entity-unique-id quality-scale checks,
these checks are not gated on quality_scale.yaml claims. Both
checks inspect every class inheriting from Entity in their
respective scopes (including shared bases and mixins/abstract bases
subclassed by other classes in the same module); see the per-rule
sections below for the module scope.
W7425: home-assistant-entity-unique-id-redundant-domain
The entity registry already keys uniqueness on (domain, platform, unique_id) where platform is the integration's name (as declared
by the "domain" field in manifest.json). Any occurrence of the
integration's name in the unique_id duplicates information already
present in the registry key.
The rule fires in every integration module (entity-platform modules,
entity.py, __init__.py, ...) when the value used for the entity's
unique id either:
- references the
DOMAINname at any depth (e.g.f"{DOMAIN}_{entry.entry_id}"), or - contains the integration's domain (read from
manifest.json) as a delimited segment of any string literal (including f-string literal parts), e.g.f"myhub-{device_id}"in an integration whose manifest declares"domain": "myhub". A segment is considered delimited when bordered by a non-alphanumeric character (_,-,.,:, space, ...) or a string boundary; letters and digits adjacent to the segment make it part of a longer identifier, so substrings like"myhubitat_..."or"myhub2"don't match.
Three locations are scanned: class-body _attr_unique_id assignments,
self._attr_unique_id = ... assignments inside method bodies, and
return values inside a unique_id property/method override.
Aliased imports (from .const import DOMAIN as MY_DOMAIN) are not
scanned.
The rule targets new unique ids. Integrations with existing unique ids in this format should keep them and disable the check on that line: migrating unique ids rewrites the entity registry and is easy to get wrong (for example, a downgrade leaves duplicate entities behind), which the cosmetic gain doesn't justify.
W7427: home-assistant-entity-unique-id-redundant-platform
In (domain, platform, unique_id) the domain field is the entity
platform (e.g. sensor, light, binary_sensor — derived from the
module the entity lives in), so embedding that name as a delimited
segment of the unique id duplicates information already in the
registry key.
The rule fires when the value used for the entity's unique id
contains the current module's platform name as a delimited segment of
any string literal. The same boundary rules as W7425 apply: a
segment is considered delimited when bordered by a non-alphanumeric
character (_, -, ., :, space, ...) or a string boundary, so
unrelated substrings like "highlight-..." or "light2" don't match
light.
Scope is narrower than W7425: only files whose integration
sub-module path keys off a known entity platform name are checked.
Both single-file platform modules (sensor.py, light.py, ...) and
platform packages (sensor/__init__.py, sensor/helpers.py, ...)
are in scope. entity.py, __init__.py at the integration root, and
other helper sub-modules are out of scope because the platform
context is ambiguous there. The three in-class scan locations are
the same as for W7425.
As for W7425, the rule targets new unique ids: existing unique ids in
this format should be kept, with the check disabled on that line.
home_assistant_entity_description_defaults checker
Detects fields in EntityDescription (and subclasses) that are explicitly
set to their default value.
C7412: home-assistant-entity-description-redundant-default
An EntityDescription field is set equal to a default already declared
anywhere in the class hierarchy; the assignment can be removed. Only the
literal defaults None, True, and False are checked; other default
values are not flagged.
home_assistant_redundant_entity_init checker
Detects entity constructors whose whole body is a super().__init__() call
that forwards every parameter through unchanged. Deleting the override leaves
the inherited constructor in place, with identical runtime behaviour.
Pylint's own useless-parent-delegation (W0246) already covers overrides
that repeat the parent's signature verbatim, but it bails out as soon as the
annotations differ. Narrowing the annotations is precisely what these
constructors do -- EntityDescription becomes a platform-specific
description, a base coordinator type becomes the integration's own -- so
W0246 never fires on them.
R7408: home-assistant-redundant-entity-init
The __init__ of a class inheriting from Entity does nothing but pass its
own parameters to super().__init__(). Remove the method:
class AriaQVmcSensor(AriaQVmcEntity, SensorEntity):
# `__init__` is redundant, the base class already takes these three
def __init__(
self,
coordinator: AriaQCoordinator,
vmc: FlowItVMCMachine,
entity_description: AriaQVmcSensorEntityDescription,
) -> None:
"""Initialize the sensor."""
super().__init__(coordinator, vmc, entity_description)
A parameter counts as forwarded when it reaches the parent under its own
name, either positionally in declaration order or as name=name; *args
and **kwargs must be forwarded as such. Anything else -- a reordering, a
renamed keyword, a transformed value, an extra or a missing argument, or any
further statement in the body -- means the constructor does work of its own
and is not flagged.
Removing the override must leave existing call sites working. The checker
finds the __init__ the class would inherit, which is the one
super().__init__ already calls, and compares the signatures. Positional
parameters must line up by index. A parameter that callers can pass by
keyword, or that the override forwards by keyword, must keep its name and
stay keyword-capable in the parent. Keyword-only parameters only need to
exist in the parent. Extra parameters in the parent are fine.
The checker skips these cases:
- A constructor with default values, because the parent's defaults may differ.
- A decorated
__init__, because the decorator can give the override a purpose. - A decorated inherited
__init__, such as an@abstractmethodconstructor. - A constructor in a decorated class, such as a
@dataclass, which makes its own__init__. - An overloaded
__init__. - A class whose
super().__init__call a subclass in the same module sends to another__init__.
home_assistant_redundant_translation_key checker
Detects entity descriptions and entity classes whose translation_key only
repeats the name the device_class already provides.
W7442: home-assistant-redundant-translation-key
Entities on the binary_sensor, button, event, number, sensor and
update platforms are named after their device class when they have no
name of their own. The name comes from entity_component.<device_class>.name
in the platform's strings.json. Sensors with the enum device class are
the exception.
An entity description that sets a device_class and a translation_key
whose name translates to the same string adds nothing:
SensorEntityDescription(
key="power",
translation_key="power", # "Power", the same as the device class name
device_class=SensorDeviceClass.POWER,
)
The same goes for an entity class that sets _attr_translation_key and
_attr_device_class in its body.
When the key is used for nothing else, remove it and its strings.json
entry. When it also holds other translations (such as states, state
attributes or the unit of measurement) or icons, or the integration's code
reads it, keep the key and remove only its name.
Entities with an explicit name (or _attr_name) are skipped, as that name
takes over once the translated name is gone. So are translated names that
another translation references with [%key:...%].
Other platforms, such as switch, don't fall back to the device class name,
so they are not checked.
home_assistant_actions_swallowed_exceptions checker
Detects action handlers that catch exceptions without re-raising. Swallowed exceptions are not surfaced to the user.
E7405: home-assistant-action-swallowed-exception
Action handlers must re-raise so the user is notified of the failure.
The checker detects empty except blocks, blocks that only log,
contextlib.suppress(...), and equivalent patterns on decorators. It does
not validate the type of exception being raised; a separate rule covers
that.
home_assistant_actions_service_registration checker
Detects services registered inside async_setup_entry rather than
async_setup.
W7414: home-assistant-service-registered-in-setup-entry
Services should be registered in async_setup so they are available for
automation validation even when no config entry is loaded. Registrations
inside helper functions that are called from async_setup_entry are
caught too, as are calls to the conventional async_setup_services helper
from services.py.
See the action-setup quality scale rule.
home_assistant_actions_services_module checker
Detects actions registered outside the integration's services.py.
W7452: home-assistant-action-registered-outside-services-module
Actions should be registered in services.py, from async_setup_services
(called from async_setup) or setup_services (called from a synchronous
setup). Module-level functions in services.py that are called from these
functions may register actions too.
W7453: home-assistant-invalid-setup-services
async_setup_services should be a synchronous function decorated with
@callback, and setup_services a synchronous function that is not, since
it runs in the executor. Both should only take hass.
home_assistant_exception_translations checker
Ensures HomeAssistantError and its subclasses use the translation system
(translation_domain, translation_key) instead of hardcoded English
strings. Also verifies that referenced translation keys exist in the
integration's strings.json and that placeholders match.
translation_domain may be a string literal, the integration's own DOMAIN,
or a constant that resolves to a string, such as
from homeassistant.components.backup import DOMAIN as BACKUP_DOMAIN. Keys
and placeholders are then checked against that domain's strings.json.
W7417: home-assistant-exception-not-translated
A HomeAssistantError subclass is raised with a hardcoded message; use
translation_domain and translation_key instead. Quality-scale-gated.
W7419: home-assistant-exception-message-with-translation
Don't pass a positional message argument when translation_key is also set;
the translation system supplies the message.
E7406: home-assistant-exception-translation-key-missing
The translation key referenced from code is missing from strings.json
under the exceptions section.
E7408: home-assistant-exception-translation-key-domain-mismatch
Both translation_key and translation_domain must be set together; only
one of the two was provided.
E7418: home-assistant-exception-placeholder-mismatch
The placeholders passed in code (e.g. translation_placeholders={...})
don't match the {placeholder} slots in the strings.json message.
home_assistant_placeholder_keys checker
Checks the keys of translation placeholder dicts. A placeholder key refers to
a {placeholder} slot in strings.json, not to a configuration key or
attribute.
A dict literal is checked when its name ends in placeholders: a keyword
argument such as description_placeholders=, an assignment such as
self.context["title_placeholders"] = {...} or placeholders = {...}, or a
dict entry such as {"title_placeholders": {...}}.
C7459: home-assistant-placeholder-key
Use a string literal for the placeholder key instead of an unrelated constant
such as CONF_USERNAME. Integrations that need a constant can use a dedicated
PLACEHOLDER_* constant or a *Placeholder enum.
# Bad
description_placeholders = {CONF_USERNAME: entry.data[CONF_USERNAME]}
# Good
description_placeholders = {"username": entry.data[CONF_USERNAME]}
# Bad
self.context["title_placeholders"] = {CONF_HOST: discovery_info.host}
# Good
self.context["title_placeholders"] = {"host": discovery_info.host}
home_assistant_target_key checker
Checks the target keys of hass.services.async_call calls: the keys of a
target= dict literal, including the keys of its exclude dict literal, and the
entity_id key of a data dict literal.
C7465: home-assistant-action-target-key
Target keys select what the action applies to, so they use TargetKey: every
constant key of the target= dict, such as ATTR_ENTITY_ID, ATTR_AREA_ID or
CommonServiceArgument.DEVICE_ID, should be the matching TargetKey member.
This also applies to the entity_id key of the data, when the action is a
<Prefix>Service enum member which declares a target in its services.yaml.
CommonServiceArgument.ENTITY_ID is for actions with their own entity_id
field.
# Bad
await hass.services.async_call(
LIGHT_DOMAIN, LightService.TURN_ON, target={ATTR_AREA_ID: "kitchen"}
)
# Good
await hass.services.async_call(
LIGHT_DOMAIN, LightService.TURN_ON, target={TargetKey.AREA_ID: "kitchen"}
)
# Bad
await hass.services.async_call(
LIGHT_DOMAIN, LightService.TURN_ON, {ATTR_ENTITY_ID: "light.kitchen"}
)
# Good
await hass.services.async_call(
LIGHT_DOMAIN, LightService.TURN_ON, {TargetKey.ENTITY_ID: "light.kitchen"}
)
home_assistant_mdi_icons checker
Validates that mdi: icon references in code and icons.json refer to
icons that actually exist in the Material Design Icons set.
E7409: home-assistant-mdi-icon-not-found
MDI icon reference in Python code does not exist in the Material Design Icons set.
E7410: home-assistant-mdi-icon-json-not-found
MDI icon reference in icons.json does not exist in the Material Design
Icons set.
home_assistant_tests_redundant_usefixtures checker
Detects @pytest.mark.usefixtures(...) decorators that duplicate a fixture
already applied module-wide, either through a module-level pytestmark
or via autouse=True on a fixture defined in a parent conftest.py.
R7403: home-assistant-tests-redundant-usefixtures
Drop the redundant @pytest.mark.usefixtures decorator; the fixture is
already applied to every test in the module.
home_assistant_tests_registry_fixtures checker
Detects test functions and pytest fixtures that call a registry helper's
async_get(hass) directly instead of using the registry fixtures defined
in tests/conftest.py (area_registry, category_registry,
device_registry, entity_registry, floor_registry, issue_registry,
label_registry).
R7404: home-assistant-tests-registry-fixtures
A test_* function or @pytest.fixture-decorated function calls
<registry>.async_get(hass) directly (e.g. er.async_get(hass)) where
<registry> resolves via a module-level
from homeassistant.helpers import ... statement to one of the seven
registry helper modules. Request the corresponding registry fixture as a
test/fixture argument instead:
async def test_entities(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
entry = entity_registry.async_get(entity_id)
Only aliases imported from homeassistant.helpers are tracked. The
checker is scoped to test modules; conftest.py files (where the
fixtures themselves are defined) and tests.helpers (which exercises the
registry helpers directly) are exempt.
home_assistant_tests_user_flow_no_data checker
Detects tests that pass a data argument when initializing a user config
flow. In production a user flow is always started without data — only
discovery flows (zeroconf, dhcp, ssdp, ...) receive data. Passing data
to a user flow init therefore exercises a code path that cannot happen in
reality.
R7405: home-assistant-tests-user-flow-no-data
A hass.config_entries.flow.async_init(...) or
hass.config_entries.subentries.async_init(...) call passes a data
keyword argument while its context sets the source to the user source.
The user source is recognized as SOURCE_USER, config_entries.SOURCE_USER,
or the literal "user", and the context may be a dict literal or a
ConfigFlowContext(source=...) call:
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_USER},
data={CONF_HOST: "127.0.0.1"}, # <-- flagged
)
Only the config-entry flow managers (config_entries.flow and
config_entries.subentries) are checked, so unrelated async_init methods
are not flagged. Discovery flows (e.g. SOURCE_ZEROCONF, SOURCE_DHCP),
dynamic source values (a variable rather than a known user source), and user
flows without
data are not flagged. The checker is scoped to test modules.
home_assistant_tests_snapshot_enable_entities checker
Detects snapshot tests that enable entities by hand. A test that calls
snapshot_platform should snapshot every entity, including the ones that
are disabled by default. The entity_registry_enabled_by_default fixture
enables them before the integration is set up, so there is no need to
update the registry and reload the config entry in the test.
R7406: home-assistant-tests-snapshot-enable-entities
A test_* function calls snapshot_platform and also calls
<registry>.async_update_entity(..., disabled_by=None):
async def test_all_entities(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
) -> None:
await setup_integration(hass, mock_config_entry)
for entry in er.async_entries_for_config_entry(
entity_registry, mock_config_entry.entry_id
):
entity_registry.async_update_entity( # <-- flagged
entry.entity_id, disabled_by=None
)
await hass.config_entries.async_reload(mock_config_entry.entry_id)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
Use the fixture instead:
@pytest.mark.usefixtures("entity_registry_enabled_by_default")
async def test_all_entities(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
) -> None:
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
Calls in nested helpers defined inside the test are checked too. Tests
that enable an entity without calling snapshot_platform (for example,
to test what happens when a user enables it) are not flagged. The checker
is scoped to test modules.
home_assistant_tests_redundant_caplog_level checker
Detects tests that set the root caplog level to DEBUG. The caplog
fixture of pytest_homeassistant already calls
caplog.set_level(logging.DEBUG), so every test that uses caplog captures
all log records at DEBUG and above.
R7407: home-assistant-tests-redundant-caplog-level
A caplog.set_level(...) or caplog.at_level(...) call sets the level to
DEBUG without a logger argument. The level is recognized as
logging.DEBUG, DEBUG imported from logging, or the string "DEBUG":
async def test_something(hass: HomeAssistant, caplog: pytest.LogCaptureFixture):
caplog.set_level(logging.DEBUG) # <-- flagged
with caplog.at_level(logging.DEBUG): # <-- flagged
...
Calls with a logger argument, or with unpacked arguments, are not
flagged, as some code sets the level of its own loggers. Other levels, like
INFO or WARNING, raise the level and are not checked either.
caplog.at_level is only checked when it is used directly in a with
statement, as only then is the block it applies to visible.
Only tests, fixtures and functions nested in them are checked. A helper
function starts at whatever level its caller left, which is not visible.
Both methods also set the level of the shared capture handler, even with a
logger, and set the root logger level and undo logging.disable. A DEBUG
call is not flagged when the level may be different at that point. A
persistent change to another level is a caplog.set_level, a
caplog.at_level that is not used directly in a with statement, a
setLevel on a logger that may be the root logger, or logging.disable,
however it is imported. The level may be different when the DEBUG call:
- follows a persistent change in the same function,
- is inside a
with caplog.at_level(...)block with another level, - is in a loop whose body makes a persistent change,
- is in a function nested in one that sets another level, or
- is a
with caplog.at_level(logging.DEBUG)block whose body makes a persistent change, which the block undoes on exit.
The checker cannot see what a fixture does to the level. Use a disable comment when a fixture raises it. The checker is scoped to test modules.
home_assistant_test_determinism checker
if and match statements inside test functions create non-deterministic
execution paths: some branches may never run, silently hiding failures.
W7409: home-assistant-test-non-deterministic
Test function contains an if or match statement. Use
@pytest.mark.parametrize to cover cases explicitly, or split into separate
test functions. if statements have several exemptions: guard clauses
(return/raise/pytest.skip/pytest.xfail/pytest.fail),
conditions that reference a function parameter, and branches that contain
no assert. match statements have no exemptions.
home_assistant_reauthentication_flow checker
Quality-scale-gated checker for the
reauthentication-flow
Silver rule. Fires only when the integration claims the rule as done.
W7410: home-assistant-missing-reauthentication-flow
Integration's config_flow.py should implement async_step_reauth.
home_assistant_parallel_updates checker
Quality-scale-gated checker for the
parallel-updates
Silver rule. Fires only when the integration claims the rule as done.
W7411: home-assistant-missing-parallel-updates
Platform module should define a module-level PARALLEL_UPDATES constant.
home_assistant_diagnostics checker
Quality-scale-gated checker for the
diagnostics
Gold rule. Fires only when the integration claims the rule as done.
W7412: home-assistant-missing-diagnostics
Integration's diagnostics.py should implement
async_get_config_entry_diagnostics or async_get_device_diagnostics.
home_assistant_config_entry_unloading checker
Quality-scale-gated checker for the
config-entry-unloading
Silver rule. Fires only when the integration claims the rule as done.
W7413: home-assistant-missing-config-entry-unloading
Integration's __init__.py should implement async_unload_entry.
home_assistant_sequential_executor_jobs checker
Detects consecutive async_add_executor_job calls in integration modules
that could be grouped into a single executor job.
W7415: home-assistant-sequential-executor-jobs
Two or more async_add_executor_job calls appearing as consecutive
statements (uninterrupted by control flow such as if/try/with/for)
should be combined into a single executor job that performs all the work,
avoiding unnecessary context switches back to the event loop between
blocking calls. The rule applies to integration modules only.
home_assistant_sequential_add_entities checker
Detects consecutive async_add_entities calls in integration modules that
could be grouped into a single call.
W7454: home-assistant-sequential-add-entities
Two or more async_add_entities (or add_entities) calls appearing as
consecutive statements (uninterrupted by control flow such as
if/try/with/for) should be combined into a single call that adds all
entities at once. Calls with different arguments besides the entities, such
as a different config_subentry_id when adding entities for multiple
subentries or a different update_before_add, cannot be combined and are not
flagged. Only calls to the callback passed to the platform setup function
(async_setup_entry, async_setup_platform or setup_platform) are checked.
The rule applies to integration modules only.
home_assistant_has_entity_name checker
Quality-scale-gated checker for the
has-entity-name
Bronze rule. Fires only when the integration claims the rule as done.
W7416: home-assistant-missing-has-entity-name
Entity class should statically guarantee _attr_has_entity_name = True:
either set at class level, set unconditionally at the top of a method, or
supplied by an entity_description whose class sets has_entity_name = True.
Conditional patterns are rejected.
home_assistant_config_flow_translations checker
Ensures that every field in a config flow, options flow, or subentry flow
form schema has a corresponding translation entry in strings.json. When
async_show_form is called with a data_schema, each key in the schema
dict should have a translation at the expected path. The checker also
handles section fields (nested under sections.<key>.data in translations).
W7428: home-assistant-config-flow-field-not-translated
A config flow form field is missing its translation in strings.json.
The expected path is config.step.<step_id>.data.<field_name> (or
config.step.<step_id>.sections.<key>.data.<field_name> for section
fields).
W7431: home-assistant-options-flow-field-not-translated
An options flow form field is missing its translation in strings.json.
The expected path is options.step.<step_id>.data.<field_name> (or
options.step.<step_id>.sections.<key>.data.<field_name> for section
fields).
W7432: home-assistant-subentry-flow-field-not-translated
A subentry flow form field is missing its translation in strings.json.
The expected path is config_subentries.<type>.step.<step_id>.data.<field_name>
(or config_subentries.<type>.step.<step_id>.sections.<key>.data.<field_name>
for section fields). The checker resolves the subentry type by finding the
ConfigFlow class's async_get_supported_subentry_types method and mapping
subentry handler class names to their type keys.
home_assistant_test_before_configure checker
Quality-scale-gated checker for the
test-before-configure
Bronze rule. Fires only when the integration claims the rule as done.
W7433: home-assistant-missing-test-before-configure
The config flow creates entries but shows no evidence of surfacing
connection failures to the user: no errors= keyword passed to a call
(with a non-empty literal or dynamic value) and no abort inside an
except handler. A failure can only be surfaced if it was detected
first, so this single footprint covers the whole test-before-configure
chain. Evidence is searched in config_flow.py and in the defining
modules of inherited flow classes from other integrations. OAuth flows
(AbstractOAuth2FlowHandler) are skipped; the token exchange is the
connection test. Integrations that rely on auto-discovery without
user-provided connection data should mark the rule exempt, per the
rule's exceptions.
home_assistant_unnecessary_format_mac checker
Detects redundant format_mac() calls inside CONNECTION_NETWORK_MAC
connection tuples that are passed to device registry API methods via
connections= keyword arguments.
W7429: home-assistant-unnecessary-format-mac
format_mac() is unnecessary when constructing a CONNECTION_NETWORK_MAC
connection tuple for a device registry API call (DeviceInfo,
async_get_or_create, async_get_device). The device registry already
normalizes MAC addresses through _normalize_connections() before
storing them, so the call is redundant.
This rule only flags tuples inside a connections= keyword argument.
Tuples used for direct comparison against device.connections (e.g.
the in operator, set intersection) are not flagged because those
comparisons bypass the device registry normalization and genuinely
need format_mac() to match the stored normalized format.
home_assistant_serial_port_selector_usb_dependency checker
Detects config flows using SerialPortSelector whose manifest.json does
not declare usb as a hard dependency.
W7430: home-assistant-serial-port-selector-usb-dependency
SerialPortSelector populates its port list via the usb/list_serial_ports
websocket command, which is only registered when the usb integration is set
up. The selector therefore requires usb as a hard dependency
("dependencies": ["usb"]); after_dependencies is not sufficient because it
does not force usb to be set up.
home_assistant_json_fixture checker
Detects tests that load a fixture and then parse it as JSON, instead of
using the dedicated JSON fixture helpers from tests.common. Only runs on
test modules. tests.common itself is exempt, since it defines the JSON
fixture helpers, which legitimately parse a loaded fixture.
W7435: home-assistant-json-fixture
A fixture loader (load_fixture, load_fixture_bytes, or
async_load_fixture) is wrapped in a JSON-parsing call (json.loads,
json.load, or the json_loads / json_loads_array / json_loads_object
helpers), e.g.:
data = json.loads(load_fixture("data.json", DOMAIN))
data = json_loads_object(await async_load_fixture(hass, "data.json"))
Use the dedicated helper that loads and parses in one step instead:
load_json_value_fixture/async_load_json_object_fixturefor a JSON value,load_json_array_fixture/async_load_json_array_fixturefor a JSON array,load_json_object_fixture/async_load_json_object_fixturefor a JSON object.
data = load_json_object_fixture("data.json", DOMAIN)
data = await async_load_json_object_fixture(hass, "data.json", DOMAIN)
home_assistant_light_color_mode checker
A LightEntity must report both supported_color_modes and a current
color_mode; setting one without the other raises HomeAssistantError at
runtime. These two checks flag each half of that inconsistency. A light
that sets neither is deliberately not flagged: the realistic both-missing
class is an abstract base, so flagging it would false-positive; the tradeoff
is that a concrete both-missing light, which also raises, is not caught.
A value is considered provided by a class when its effective declaration,
resolved in MRO order and excluding LightEntity's own None defaults, is a
non-None class-body _attr_... assignment, a self._attr_... = ...
assignment in a method body, or a property/method override of the public
name. Subclass shadowing is respected: a subclass that assigns the
_attr_... to None nullifies a non-None value inherited from an
ancestor. Mixin/abstract bases that are subclassed by another class in the
same module are exempted, on the assumption that the concrete subclass is the
runtime entity (and may supply the missing half).
W7436: home-assistant-light-missing-color-mode
The light provides supported_color_modes but no color_mode. At runtime
LightEntity.state_attributes raises HomeAssistantError ("does not report a
color mode") whenever the light is on and color_mode is None -- there is
no inference of the mode from a single supported mode, so this holds even for
lights that support only ONOFF or BRIGHTNESS. Set _attr_color_mode or
override the color_mode property.
W7437: home-assistant-light-missing-supported-color-modes
The light provides color_mode but no supported_color_modes. At runtime
LightEntity._light_internal_supported_color_modes raises HomeAssistantError
("does not set supported color modes") from both state_attributes and
capability_attributes whenever supported_color_modes is None. Set
_attr_supported_color_modes or override the supported_color_modes property.
home_assistant_enforce_config_flow_no_connection_class checker
Detects config flow classes that set CONNECTION_CLASS.
W7438: home-assistant-config-flow-connection-class
CONNECTION_CLASS is no longer used by Home Assistant and should not be set
on config flows. Remove the attribute.
home-assistant-step_id-match-method checker
Detects config flows using a step_id parameter different than the method it is
currently in.
W7443: home-assistant-step_id-match-method
Check the step_id parameter for all calls to async_show_form,
async_external_step, async_show_progress and async_show_menu.
The step_id parameter should be same as the method it is in.
For example: step_id="user" should be used in async_step_user
home_assistant_flow_start_helpers checker
Enforces the use of MockConfigEntry helpers to start reauth and
reconfigure flows in integration tests.
W7445: home-assistant-test-flow-start-helper
Tests must not start a reauth or reconfigure flow by calling
hass.config_entries.flow.async_init with a hand-built context
("source": SOURCE_REAUTH / SOURCE_RECONFIGURE). Use
entry.start_reauth_flow(hass) or entry.start_reconfigure_flow(hass)
instead; they build the same context Home Assistant uses at runtime.
# Bad
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_REAUTH, "entry_id": entry.entry_id},
data=entry.data,
)
# Good
result = await entry.start_reauth_flow(hass)