Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ImmutableValidatedObject: Support nested Mapping types #1573

Merged
merged 1 commit into from
Dec 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 27 additions & 14 deletions nixops/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@
import re
import typing
import typeguard # type: ignore
import inspect
import shlex
import collections.abc
from inspect import isclass
from typing import (
Callable,
List,
Expand Down Expand Up @@ -149,21 +150,33 @@ def _transform_value(key: Any, value: Any) -> Any:
if not ann:
return value

if inspect.isclass(ann) and issubclass(ann, ImmutableValidatedObject):
if isclass(ann) and issubclass(ann, ImmutableValidatedObject):
value = ann(**value)

# Support Sequence[ImmutableValidatedObject]
if isinstance(value, tuple) and not isinstance(ann, str):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This rejects strings, but in the new code all Sequences are matched, because

>>> isinstance("hi", collections.abc.Sequence)
True

Could you exclude strings from the match, to be sure, or perhaps explain why strings don't occur here if that's the case?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, not all Sequences are matched, only those explicitly annotated as such. This seems more in line with what is expected from the comments, tests and existing code, afaict.

>>> import typing
>>> import collections.abc
>>> class test_class:
...     test_string: str
...     test_tuple: typing.Tuple[test_class]
...     test_list: typing.List[test_class]
...     test_sequence: typing.Sequence[test_class]
...     test_dict: typing.Dict[str, test_class]
...     test_mapping: typing.Mapping[str, test_class]
...
>>> for k, v in typing.get_type_hints(test_class).items():
...     match typing.get_origin(v):
...             case collections.abc.Sequence | collections.abc.Mapping:
...                     print(f"{k}, {v}")
... 
test_sequence, typing.Sequence[__main__.test_class]
test_mapping, typing.Mapping[str, __main__.test_class]

new_value = []
for v in value:
for subann in ann.__args__: # type: ignore
if inspect.isclass(subann) and issubclass(
subann, ImmutableValidatedObject
):
new_value.append(subann(**v))
else:
new_value.append(v)
value = tuple(new_value)
# Support containers of ImmutableValidatedObjects
match typing.get_origin(ann):

case collections.abc.Sequence:
sequence: List = []
for v in value:
for subann in typing.get_args(ann):
if isclass(subann) and issubclass(
subann, ImmutableValidatedObject
):
sequence.append(subann(**v))
else:
sequence.append(v)
value = tuple(sequence)

case collections.abc.Mapping:
_, value_ann = typing.get_args(ann)
if isclass(value_ann) and issubclass(
value_ann, ImmutableValidatedObject
):
mapping: Dict = {}
for k, v in value.items():
mapping[k] = value_ann(**v)
value = mapping

typeguard.check_type(value, ann)

Expand Down
14 changes: 12 additions & 2 deletions tests/unit/test_util.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, Sequence
from typing import Any, Sequence, Mapping
import json
from nixops.logger import Logger
from io import StringIO
Expand Down Expand Up @@ -121,4 +121,14 @@ class B(A):
class WithSequence(util.ImmutableValidatedObject):
subs: Sequence[SubResource]

WithSequence(subs=[SubResource(x=1), SubResource(x=2)])
seq = WithSequence(subs=[{"x": 1}, {"x": 2}])
for i in seq.subs:
self.assertIsInstance(i, SubResource)

# Test Mapping[str, ImmutableValidatedObject]
class WithMapping(util.ImmutableValidatedObject):
mapping: Mapping[str, SubResource]

mapped = WithMapping(mapping={"aaa": {"x": 1}, "bbb": {"x": 2}})
for _, v in mapped.mapping.items():
self.assertIsInstance(v, SubResource)
Loading