Skip to content

Commit

Permalink
Fix bug with JSON schema for sequence of discriminated union (#7647)
Browse files Browse the repository at this point in the history
  • Loading branch information
dmontagu committed Sep 26, 2023
1 parent 07b23ef commit 734f7ad
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 13 deletions.
10 changes: 1 addition & 9 deletions pydantic/_internal/_generate_schema.py
Expand Up @@ -1252,12 +1252,6 @@ def _sequence_schema(self, sequence_type: Any) -> core_schema.CoreSchema:
"""Generate schema for a Sequence, e.g. `Sequence[int]`."""
item_type = self._get_first_arg_or_any(sequence_type)

def json_schema_func(_schema: CoreSchemaOrField, handler: GetJsonSchemaHandler) -> JsonSchemaValue:
items_schema = self._generate_schema(item_type)
return handler(core_schema.list_schema(items_schema))

metadata = build_metadata_dict(js_functions=[json_schema_func])

list_schema = core_schema.list_schema(self.generate_schema(item_type))
python_schema = core_schema.is_instance_schema(typing.Sequence, cls_repr='Sequence')
if item_type != Any:
Expand All @@ -1266,9 +1260,7 @@ def json_schema_func(_schema: CoreSchemaOrField, handler: GetJsonSchemaHandler)
python_schema = core_schema.chain_schema(
[python_schema, core_schema.no_info_wrap_validator_function(sequence_validator, list_schema)],
)
return core_schema.json_or_python_schema(
json_schema=list_schema, python_schema=python_schema, metadata=metadata
)
return core_schema.json_or_python_schema(json_schema=list_schema, python_schema=python_schema)

def _iterable_schema(self, type_: Any) -> core_schema.GeneratorSchema:
"""Generate a schema for an `Iterable`."""
Expand Down
19 changes: 15 additions & 4 deletions tests/test_discriminated_union.py
Expand Up @@ -1296,17 +1296,17 @@ class Model(BaseModel):
'$defs': {
'Cat': {
'properties': {
'meows': {'title': 'Meows', 'type': 'integer'},
'pet_type': {'const': 'cat', 'title': 'Pet Type'},
'meows': {'title': 'Meows', 'type': 'integer'},
},
'required': ['pet_type', 'meows'],
'title': 'Cat',
'type': 'object',
},
'Dog': {
'properties': {
'barks': {'title': 'Barks', 'type': 'number'},
'pet_type': {'const': 'dog', 'title': 'Pet Type'},
'barks': {'title': 'Barks', 'type': 'number'},
},
'required': ['pet_type', 'barks'],
'title': 'Dog',
Expand All @@ -1323,12 +1323,23 @@ class Model(BaseModel):
},
},
'properties': {
'n': {'title': 'N', 'type': 'integer'},
'pet': {
'items': {'anyOf': [{'$ref': '#/$defs/Cat'}, {'$ref': '#/$defs/Dog'}, {'$ref': '#/$defs/Lizard'}]},
'items': {
'discriminator': {
'mapping': {
'cat': '#/$defs/Cat',
'dog': '#/$defs/Dog',
'lizard': '#/$defs/Lizard',
'reptile': '#/$defs/Lizard',
},
'propertyName': 'pet_type',
},
'oneOf': [{'$ref': '#/$defs/Cat'}, {'$ref': '#/$defs/Dog'}, {'$ref': '#/$defs/Lizard'}],
},
'title': 'Pet',
'type': 'array',
},
'n': {'title': 'N', 'type': 'integer'},
},
'required': ['pet', 'n'],
'title': 'Model',
Expand Down

0 comments on commit 734f7ad

Please sign in to comment.