Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,9 @@ Each release links to full notes on the
only string values, a `Literal` of strings, a `NewType` or `type` alias of
`str`, and a union whose arms other than `None` are all `str` or one of these
do not warn ([#662](https://github.com/awslabs/stickler/issues/662)).
In `to_json_schema()`, a list whose element is such a union with a `None`
arm, such as `List[Union[str, Literal["b"], None]]`, writes nullable items,
so the rebuilt model accepts its `None` items.
`to_stickler_config()` also warns for a list element type
`model_from_json()` cannot read, such as `List[Decimal]`. `model_from_json()`
turns a list default on a tuple field back into a tuple
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,12 @@
from .evaluator_format_helper import EvaluatorFormatHelper
from .metrics_helper import MetricsHelper
from .null_helper import NullHelper
from .optional_annotation import union_args, unwrap_annotated, unwrap_optional
from .optional_annotation import (
is_union,
union_args,
unwrap_annotated,
unwrap_optional,
)
from .rich_value_helper import RichValueHelper
from .threshold_helper import model_identity as _model_identity
from .threshold_helper import warn_if_threshold_is_zero as _warn_if_threshold_is_zero
Expand Down Expand Up @@ -2305,6 +2310,15 @@ def to_json_schema(cls) -> Dict[str, Any]:
# Annotated is stripped for the same reason, so
# `List[Annotated[Card, "m"]]` reaches the recursive branch.
_, element_is_nullable = cls._unwrap_optional(unwrap_annotated(args[0]))
# A union of several arms plus None is nullable too.
# `_unwrap_optional` reads only `Optional[T]`, so
# `List[Union[str, Literal["b"], None]]` wrote string items
# without null, and the rebuilt model rejected its None items.
element_annotation = unwrap_annotated(args[0])
if is_union(element_annotation) and type(None) in get_args(
element_annotation
):
element_is_nullable = True
element_type = ConfigurationHelper.strip_annotation_wrappers(args[0])

if cls._is_structured_model_type(element_type):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -654,6 +654,31 @@ class Holder(StructuredModel):
assert "field 'Holder.items'" in unmapped[0]


@pytest.mark.parametrize(
"element",
[
Optional[str],
Union[str, Literal["b"], None],
Union[Letter, str, None],
Annotated[Union[str, Literal["b"], None], "m"],
],
)
def test_a_list_element_with_a_none_arm_keeps_its_none_items(element):
# The warning rule skips a None arm, so the items must carry null. A union
# of several arms plus None wrote string items without it, and the rebuilt
# model rejected the None items the original accepts.
class Holder(StructuredModel):
items: List[element] = ComparableField()

with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
schema = Holder.to_json_schema()
assert not [w for w in caught if "has no export type" in str(w.message)]
assert schema["properties"]["items"]["items"] == {"type": ["string", "null"]}
rebuilt = StructuredModel.from_json_schema(json.loads(json.dumps(schema)))
assert rebuilt(items=["a", None]).items == ["a", None]


@pytest.mark.parametrize(
"annotation, comparator, default",
[
Expand Down