Skip to content

Commit

Permalink
Fix schema for set and frozenset with default value (#4155)
Browse files Browse the repository at this point in the history
* Fix schema for Set with default value

* add changelog

* Add frozenset to schema mapping docs
  • Loading branch information
aminalaee committed Aug 8, 2022
1 parent b42fae0 commit 65a1381
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 5 deletions.
1 change: 1 addition & 0 deletions changes/4155-aminalaee.md
@@ -0,0 +1 @@
Fix JSON schema for `set` and `frozenset` when they include default values.
7 changes: 7 additions & 0 deletions docs/build/schema_mapping.py
Expand Up @@ -74,6 +74,13 @@
'JSON Schema Validation',
''
],
[
'frozenset',
'array',
{'items': {}, 'uniqueItems': True},
'JSON Schema Validation',
''
],
[
'List[str]',
'array',
Expand Down
4 changes: 2 additions & 2 deletions pydantic/schema.py
Expand Up @@ -77,7 +77,7 @@
is_none_type,
is_union,
)
from .utils import ROOT_KEY, get_model, lenient_issubclass, sequence_like
from .utils import ROOT_KEY, get_model, lenient_issubclass

if TYPE_CHECKING:
from .dataclasses import Dataclass
Expand Down Expand Up @@ -970,7 +970,7 @@ def encode_default(dft: Any) -> Any:
return dft.value
elif isinstance(dft, (int, float, str)):
return dft
elif sequence_like(dft):
elif isinstance(dft, (list, tuple)):
t = dft.__class__
seq_args = (encode_default(v) for v in dft)
return t(*seq_args) if is_namedtuple(t) else t(seq_args)
Expand Down
8 changes: 5 additions & 3 deletions tests/test_schema.py
Expand Up @@ -530,13 +530,15 @@ def test_set():
class Model(BaseModel):
a: Set[int]
b: set
c: set = {1}

assert Model.schema() == {
'title': 'Model',
'type': 'object',
'properties': {
'a': {'title': 'A', 'type': 'array', 'uniqueItems': True, 'items': {'type': 'integer'}},
'b': {'title': 'B', 'type': 'array', 'items': {}, 'uniqueItems': True},
'c': {'title': 'C', 'type': 'array', 'items': {}, 'default': [1], 'uniqueItems': True},
},
'required': ['a', 'b'],
}
Expand Down Expand Up @@ -2187,13 +2189,13 @@ class Model(BaseModel):
'properties': {
'a': {
'title': 'A',
'default': frozenset({1, 2, 3}),
'default': [1, 2, 3],
'type': 'array',
'items': {'type': 'integer'},
'uniqueItems': True,
},
'b': {'title': 'B', 'default': frozenset({1, 2, 3}), 'type': 'array', 'items': {}, 'uniqueItems': True},
'c': {'title': 'C', 'default': frozenset({1, 2, 3}), 'type': 'array', 'items': {}, 'uniqueItems': True},
'b': {'title': 'B', 'default': [1, 2, 3], 'type': 'array', 'items': {}, 'uniqueItems': True},
'c': {'title': 'C', 'default': [1, 2, 3], 'type': 'array', 'items': {}, 'uniqueItems': True},
'd': {'title': 'D', 'type': 'array', 'items': {}, 'uniqueItems': True},
},
'required': ['d'],
Expand Down

0 comments on commit 65a1381

Please sign in to comment.