From e5eb8de316a105927040e58c499122e5a6ed2684 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Sat, 5 Dec 2026 01:15:13 +0100 Subject: [PATCH] fix: a NotRequired key is optional at runtime too (#144) Eight modules postponed their annotations, so TypedDict saw each NotRequired as a string and recorded the key as required: __optional_keys__ of KernelFactsDict and eight more shapes was empty. mypy reads the source and was right; runtime introspection was not. The modules evaluate their annotations again, and a test walks every TypedDict in the package for an annotation it could not read. --- CHANGELOG.md | 9 ++++ napalm_device_types/host_repairs.py | 4 +- napalm_device_types/kernel_models.py | 4 +- napalm_device_types/lldp.py | 4 +- napalm_device_types/log_sources.py | 4 +- napalm_device_types/scheduled_jobs.py | 4 +- napalm_device_types/share_models.py | 4 +- napalm_device_types/updates.py | 4 +- napalm_device_types/zabbix_agent.py | 4 +- tests/test_typed_dict_optional_keys.py | 71 ++++++++++++++++++++++++++ 10 files changed, 96 insertions(+), 16 deletions(-) create mode 100644 tests/test_typed_dict_optional_keys.py diff --git a/CHANGELOG.md b/CHANGELOG.md index e17f201..07cb4b6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,15 @@ recorded here; their history is the git log. ## [Unreleased] +### Fixed +- A key declared `NotRequired` is optional at runtime too: `__optional_keys__` of + `KernelFactsDict`, `HostRepairResultDict`, `LldpNeighborDict`, `LogSourceDict`, + `ScheduledJobDict`, `ScheduledJobSpecDict`, `NASShareDict`, `UpdateHistoryPackageDict` + and `ZabbixAgentSettingsDict` was empty, and their optional keys read as required. Their + modules postponed annotations (`from __future__ import annotations`), and TypedDict + sees `NotRequired` only in an evaluated annotation. Type checking was not affected. A + test now walks every TypedDict in the package for an annotation it could not read. + ## [4.58.1] - 2026-12-03 ### Fixed diff --git a/napalm_device_types/host_repairs.py b/napalm_device_types/host_repairs.py index 6eb332f..70c1a41 100644 --- a/napalm_device_types/host_repairs.py +++ b/napalm_device_types/host_repairs.py @@ -21,8 +21,8 @@ Declared under ``if TYPE_CHECKING``: a contract, not a placeholder (see the pack docstring). Not mixed into any role base. """ -from __future__ import annotations - +# No ``from __future__ import annotations``: TypedDict tells a ``NotRequired`` key only +# from an evaluated annotation (``HostRepairResultDict.__optional_keys__``). from collections.abc import Callable, Sequence from typing import TYPE_CHECKING, NotRequired diff --git a/napalm_device_types/kernel_models.py b/napalm_device_types/kernel_models.py index a2c6488..ba6bdf0 100644 --- a/napalm_device_types/kernel_models.py +++ b/napalm_device_types/kernel_models.py @@ -5,8 +5,8 @@ it: the reading grew its live patches (NetOrk/netork#2701), and ``models`` is at recorded size. """ -from __future__ import annotations - +# No ``from __future__ import annotations``: TypedDict tells a ``NotRequired`` key only +# from an evaluated annotation (``KernelFactsDict.__optional_keys__``). from typing import NotRequired from typing_extensions import TypedDict diff --git a/napalm_device_types/lldp.py b/napalm_device_types/lldp.py index 44b0e26..a212e90 100644 --- a/napalm_device_types/lldp.py +++ b/napalm_device_types/lldp.py @@ -8,8 +8,8 @@ phone and the PC behind it, an unmanaged switch) is several rows, and stays several entries in both shapes. """ -from __future__ import annotations - +# No ``from __future__ import annotations``: TypedDict tells a ``NotRequired`` key only +# from an evaluated annotation (``LldpNeighborDict.__optional_keys__``). import re from collections.abc import Iterable from typing import NotRequired, TypedDict diff --git a/napalm_device_types/log_sources.py b/napalm_device_types/log_sources.py index 53d0225..d1814f0 100644 --- a/napalm_device_types/log_sources.py +++ b/napalm_device_types/log_sources.py @@ -40,8 +40,8 @@ short must never read as logs that went away, and so must a host whose :class:`LogSourcesUnavailable`. """ -from __future__ import annotations - +# No ``from __future__ import annotations``: TypedDict tells a ``NotRequired`` key only +# from an evaluated annotation (``LogSourceDict.__optional_keys__``). import re from datetime import UTC, datetime from shlex import quote diff --git a/napalm_device_types/scheduled_jobs.py b/napalm_device_types/scheduled_jobs.py index 7ea907c..acd99b6 100644 --- a/napalm_device_types/scheduled_jobs.py +++ b/napalm_device_types/scheduled_jobs.py @@ -23,8 +23,8 @@ saw. The driver reads the job again right before it writes and raises :class:`ScheduledJobChanged` when the definition differs. """ -from __future__ import annotations - +# No ``from __future__ import annotations``: TypedDict tells a ``NotRequired`` key only +# from an evaluated annotation (``ScheduledJobDict.__optional_keys__``). import hashlib import json import re diff --git a/napalm_device_types/share_models.py b/napalm_device_types/share_models.py index a0515dd..21f4e76 100644 --- a/napalm_device_types/share_models.py +++ b/napalm_device_types/share_models.py @@ -4,8 +4,8 @@ A storage driver's ``get_shares`` and a Linux host's (``PosixSharesMixin``) answ :class:`NASShareDict`; ``models`` re-exports both names, where they used to live. """ -from __future__ import annotations - +# No ``from __future__ import annotations``: TypedDict tells a ``NotRequired`` key only +# from an evaluated annotation (``NASShareDict.__optional_keys__``). from typing import NotRequired from typing_extensions import TypedDict diff --git a/napalm_device_types/updates.py b/napalm_device_types/updates.py index a7163a3..b8a0114 100644 --- a/napalm_device_types/updates.py +++ b/napalm_device_types/updates.py @@ -10,8 +10,8 @@ Nothing exists at runtime until a concrete driver implements it, so mixing this class in can never shadow a working implementation from a sibling base. """ -from __future__ import annotations - +# No ``from __future__ import annotations``: TypedDict tells a ``NotRequired`` key only +# from an evaluated annotation (``UpdateHistoryPackageDict.__optional_keys__``). from collections.abc import Callable from typing import TYPE_CHECKING, Any, Literal, NotRequired diff --git a/napalm_device_types/zabbix_agent.py b/napalm_device_types/zabbix_agent.py index 8db6bfe..d375df1 100644 --- a/napalm_device_types/zabbix_agent.py +++ b/napalm_device_types/zabbix_agent.py @@ -26,8 +26,8 @@ with the rpm in an ``x86_64`` directory. The release line is the server's: an ag may be older than its server, not newer. """ -from __future__ import annotations - +# No ``from __future__ import annotations``: TypedDict tells a ``NotRequired`` key only +# from an evaluated annotation (``ZabbixAgentSettingsDict.__optional_keys__``). import re import shlex from typing import NotRequired, TypedDict diff --git a/tests/test_typed_dict_optional_keys.py b/tests/test_typed_dict_optional_keys.py new file mode 100644 index 0000000..4b59e25 --- /dev/null +++ b/tests/test_typed_dict_optional_keys.py @@ -0,0 +1,71 @@ +"""A ``NotRequired`` key is optional at runtime too. + +TypedDict tells a ``NotRequired`` key only from an evaluated annotation. Under +``from __future__ import annotations`` every annotation is a string, the wrapper goes +unseen, and the key lands in ``__required_keys__``. mypy reads the source and is not +fooled; runtime introspection (``__optional_keys__``) is. +""" + +import importlib +import pkgutil +from typing import Any, ForwardRef + +import pytest +import typing_extensions + +import napalm_device_types +from napalm_device_types.host_repairs import HostRepairResultDict +from napalm_device_types.kernel_models import KernelFactsDict +from napalm_device_types.lldp import LldpNeighborDict +from napalm_device_types.log_sources import LogSourceDict +from napalm_device_types.scheduled_jobs import ScheduledJobDict, ScheduledJobSpecDict +from napalm_device_types.share_models import NASShareDict +from napalm_device_types.updates import UpdateHistoryPackageDict +from napalm_device_types.zabbix_agent import ZabbixAgentSettingsDict + +OPTIONAL_KEYS: dict[Any, set[str]] = { + KernelFactsDict: {"live_patches"}, + HostRepairResultDict: {"error"}, + LldpNeighborDict: {"mac"}, + LogSourceDict: {"channel"}, + ScheduledJobDict: {"name", "description", "last_run", "last_result", "next_run"}, + ScheduledJobSpecDict: {"description"}, + NASShareDict: {"service", "export", "access", "guest"}, + UpdateHistoryPackageDict: {"title"}, + ZabbixAgentSettingsDict: {"hostname", "release", "active_only"}, +} + + +@pytest.mark.parametrize("typed_dict", list(OPTIONAL_KEYS), ids=lambda value: value.__name__) +def test_not_required_keys_are_optional_at_runtime(typed_dict: Any) -> None: + optional = OPTIONAL_KEYS[typed_dict] + assert typed_dict.__optional_keys__ == optional + assert not optional & typed_dict.__required_keys__ + + +def _typed_dicts() -> list[Any]: + found = [] + for info in pkgutil.iter_modules(napalm_device_types.__path__): + module = importlib.import_module(f"napalm_device_types.{info.name}") + for value in vars(module).values(): + if ( + isinstance(value, type) + and typing_extensions.is_typeddict(value) + and value.__module__ == module.__name__ + ): + found.append(value) + return found + + +def test_no_typed_dict_keeps_not_required_as_a_string() -> None: + """Every module: a ``NotRequired`` the TypedDict could not see is a required key.""" + unseen = [ + f"{typed_dict.__module__}.{typed_dict.__qualname__}.{key}" + for typed_dict in _typed_dicts() + for key, annotation in typed_dict.__dict__.get("__annotations__", {}).items() + if isinstance(annotation, str | ForwardRef) + and str(getattr(annotation, "__forward_arg__", annotation)).startswith( + ("NotRequired[", "Required[") + ) + ] + assert unseen == []