Add pylint check for noqa F401 in modules defining __all__ (#186698)

This commit is contained in:
epenet
2026-10-16 08:22:40 -04:00
committed by GitHub
parent 5fbb1dbd2d
commit be50b3efe5
3 changed files with 291 additions and 0 deletions
+9
View File
@@ -89,6 +89,7 @@ Every check has a code following the
| `C7413` | [`home-assistant-duplicate-const`](#c7413-home-assistant-duplicate-const) | Constant duplicates one in `homeassistant.const` with the same value |
| `C7414` | [`home-assistant-enforce-utcnow`](#c7414-home-assistant-enforce-utcnow) | Use `homeassistant.util.dt.utcnow` instead of `datetime.now(UTC)` |
| `C7415` | [`home-assistant-domain-argument`](#c7415-home-assistant-domain-argument) | Domain argument in tests should be a domain constant or variable |
| `C7416` | [`home-assistant-noqa-f401-with-all`](#c7416-home-assistant-noqa-f401-with-all) | List re-exported names in `__all__` instead of using `# noqa: F401` |
| `C7425` | [`home-assistant-enforce-now`](#c7425-home-assistant-enforce-now) | Use `homeassistant.util.dt.now` instead of `datetime.now(<tz>)` |
| `C7427` | [`home-assistant-enforce-naive-now`](#c7427-home-assistant-enforce-naive-now) | Use `homeassistant.util.dt.naive_now` instead of `datetime.now()` |
| `E7401` | [`home-assistant-invalid-inheritance`](#e7401-home-assistant-invalid-inheritance) | Invalid entity class inheritance chain |
@@ -211,6 +212,14 @@ Aliased `DOMAIN` import from another integration should use a descriptive 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_enforce_type_hints` checker
@@ -1,6 +1,7 @@
"""Checker for import conventions."""
from dataclasses import dataclass
from pathlib import Path
import re
from astroid import nodes
@@ -126,6 +127,8 @@ _OBSOLETE_IMPORT: dict[str, list[ObsoleteImportMatch]] = {
],
}
_NOQA_F401 = re.compile(r"#\s*noqa:[^#]*\bF401\b")
_IGNORE_ROOT_IMPORT = (
"bluetooth",
"device_tracker",
@@ -168,6 +171,27 @@ _FORCE_NAMESPACE_IMPORT: dict[str, NamespaceAlias] = {
}
def _imports_only_submodules(
module: nodes.Module, import_node: nodes.Import | nodes.ImportFrom
) -> bool:
"""Return True for `from . import x, y` where all names are submodules.
Such imports preload platforms for their side effect and re-export nothing.
"""
if (
not isinstance(import_node, nodes.ImportFrom)
or import_node.level != 1
or import_node.modname
or not module.file
):
return False
package_dir = Path(module.file).parent
return all(
(package_dir / f"{name}.py").is_file() or (package_dir / name).is_dir()
for name, _ in import_node.names
)
class HassImportsFormatChecker(BaseChecker):
"""Checker for imports."""
@@ -211,6 +235,13 @@ class HassImportsFormatChecker(BaseChecker):
"home-assistant-import-constant-unnecessary-alias",
"Used when a constant alias is unnecessary",
),
"C7416": (
"Module defines `__all__`: list the re-exported names in `__all__` "
"instead of using `# noqa: F401`",
"home-assistant-noqa-f401-with-all",
"Used when an import in an integration module that defines __all__ "
"is marked with noqa: F401",
),
}
options = ()
@@ -227,6 +258,26 @@ class HassImportsFormatChecker(BaseChecker):
parsed_module = parse_module(node.name, include_test=True)
self.current_component = parsed_module.domain if parsed_module else None
if "__all__" in node.locals and parse_module(node.name):
self._check_for_noqa_f401_with_all(node)
def _check_for_noqa_f401_with_all(self, node: nodes.Module) -> None:
"""Check for `# noqa: F401` markers in a module defining __all__."""
with node.stream() as stream:
lines = stream.read().decode().splitlines()
for import_node in node.nodes_of_class((nodes.Import, nodes.ImportFrom)):
# Local imports cannot be exported through the module's __all__
if import_node.scope() is not node:
continue
if not any(
_NOQA_F401.search(line)
for line in lines[import_node.fromlineno - 1 : import_node.tolineno]
):
continue
if _imports_only_submodules(node, import_node):
continue
self.add_message("home-assistant-noqa-f401-with-all", node=import_node)
def visit_import(self, node: nodes.Import) -> None:
"""Check for improper `import _` invocations."""
for other_module, _alias in node.names:
+231
View File
@@ -1,5 +1,8 @@
"""Tests for pylint hass_imports plugin."""
from pathlib import Path
import textwrap
import astroid
from pylint.checkers import BaseChecker
import pylint.testutils
@@ -369,3 +372,231 @@ def test_domain_alias(
imports_checker.visit_import(import_node)
else:
imports_checker.visit_importfrom(import_node)
@pytest.mark.parametrize(
("module_name", "code"),
[
pytest.param(
"homeassistant.components.pylint_test",
"""
from .const import DOMAIN, SERVICE # noqa: F401
__all__ = ["DOMAIN"]
""",
id="noqa_with_all",
),
pytest.param(
"homeassistant.components.pylint_test",
"""
from .const import (
DOMAIN,
SERVICE, # noqa: F401
)
__all__ = ["DOMAIN"]
""",
id="per_name_noqa_with_all",
),
pytest.param(
"homeassistant.components.pylint_test",
"""
from .const import DOMAIN, SERVICE # noqa: E501, F401
__all__ = ["DOMAIN"]
""",
id="combined_noqa_with_all",
),
pytest.param(
"homeassistant.components.pylint_test",
"""
from . import CONSTANT, sensor # noqa: F401
__all__ = ["DOMAIN"]
""",
id="mixed_submodule_noqa_with_all",
),
pytest.param(
"homeassistant.components.pylint_test.sensor",
"""
from .const import DOMAIN, SERVICE # noqa: F401
__all__ = ["DOMAIN"]
""",
id="noqa_with_all_in_submodule",
),
],
)
def test_bad_noqa_f401_with_all(
linter: UnittestLinter,
imports_checker: BaseChecker,
tmp_path: Path,
module_name: str,
code: str,
) -> None:
"""Ensure `# noqa: F401` is reported in modules defining __all__."""
(tmp_path / "sensor.py").touch()
root_node = astroid.parse(
textwrap.dedent(code), module_name, str(tmp_path / "__init__.py")
)
import_node = root_node.body[0]
with assert_adds_messages(
linter,
pylint.testutils.MessageTest(
msg_id="home-assistant-noqa-f401-with-all",
node=import_node,
line=import_node.lineno,
col_offset=import_node.col_offset,
end_line=import_node.end_lineno,
end_col_offset=import_node.end_col_offset,
),
):
imports_checker.visit_module(root_node)
@pytest.mark.parametrize(
("module_name", "code"),
[
pytest.param(
"homeassistant.components.pylint_test",
"""
from .const import DOMAIN, SERVICE # noqa: F401
""",
id="noqa_without_all",
),
pytest.param(
"homeassistant.components.pylint_test",
"""
from .const import DOMAIN, SERVICE
__all__ = ["DOMAIN", "SERVICE"]
""",
id="all_without_noqa",
),
pytest.param(
"homeassistant.components.pylint_test",
"""
from . import sensor, switch # noqa: F401
__all__ = ["DOMAIN"]
""",
id="submodule_preload",
),
pytest.param(
"tests.components.pylint_test",
"""
from .const import DOMAIN, SERVICE # noqa: F401
__all__ = ["DOMAIN"]
""",
id="test_module",
),
pytest.param(
"homeassistant.helpers.pylint_test",
"""
from .const import DOMAIN, SERVICE # noqa: F401
__all__ = ["DOMAIN"]
""",
id="not_an_integration",
),
pytest.param(
"homeassistant.components.pylint_test",
"""
__all__ = ["DOMAIN"]
def check() -> bool:
import pylint_test_library # noqa: F401
return True
""",
id="function_local_import",
),
pytest.param(
"homeassistant.components.pylint_test",
"""
__all__ = ["DOMAIN"]
class Check:
from .const import SERVICE # noqa: F401
""",
id="class_local_import",
),
],
)
def test_good_noqa_f401_with_all(
linter: UnittestLinter,
imports_checker: BaseChecker,
tmp_path: Path,
module_name: str,
code: str,
) -> None:
"""Ensure allowed `# noqa: F401` usages are not reported."""
(tmp_path / "sensor.py").touch()
(tmp_path / "switch").mkdir()
root_node = astroid.parse(
textwrap.dedent(code), module_name, str(tmp_path / "__init__.py")
)
with assert_no_messages(linter):
imports_checker.visit_module(root_node)
def test_good_noqa_f401_with_all_sibling_preload(
linter: UnittestLinter,
imports_checker: BaseChecker,
tmp_path: Path,
) -> None:
"""Ensure preloading sibling submodules from an ordinary module passes."""
(tmp_path / "sensor.py").touch()
root_node = astroid.parse(
textwrap.dedent(
"""
from . import sensor # noqa: F401
__all__ = ["DOMAIN"]
"""
),
"homeassistant.components.pylint_test.api",
str(tmp_path / "api.py"),
)
with assert_no_messages(linter):
imports_checker.visit_module(root_node)
def test_bad_noqa_f401_with_all_module_level_block(
linter: UnittestLinter,
imports_checker: BaseChecker,
tmp_path: Path,
) -> None:
"""Ensure imports in module-level blocks are still reported."""
root_node = astroid.parse(
textwrap.dedent(
"""
try:
from .const import SERVICE # noqa: F401
except ImportError:
pass
__all__ = ["DOMAIN"]
"""
),
"homeassistant.components.pylint_test",
str(tmp_path / "__init__.py"),
)
import_node = root_node.body[0].body[0]
with assert_adds_messages(
linter,
pylint.testutils.MessageTest(
msg_id="home-assistant-noqa-f401-with-all",
node=import_node,
line=import_node.lineno,
col_offset=import_node.col_offset,
end_line=import_node.end_lineno,
end_col_offset=import_node.end_col_offset,
),
):
imports_checker.visit_module(root_node)