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.
This commit is contained in:
1 parent
80a5efc494
commit
e5eb8de316
10 files changed
+96
-16
No files matched your search
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 == []
|
||||
Reference in new issue
Block a user