Skip to content

Commit

Permalink
Remove default factory call results from the JSON schema (#6126)
Browse files Browse the repository at this point in the history
  • Loading branch information
dmontagu committed Jun 14, 2023
1 parent 23db871 commit b618dbd
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 13 deletions.
7 changes: 1 addition & 6 deletions docs/usage/dataclasses.md
Expand Up @@ -64,12 +64,7 @@ print(TypeAdapter(User).json_schema())
'description': 'do not lie!',
'title': 'The age of the user',
},
'friends': {
'default': [0],
'items': {'type': 'integer'},
'title': 'Friends',
'type': 'array',
},
'friends': {'items': {'type': 'integer'}, 'title': 'Friends', 'type': 'array'},
'height': {
'anyOf': [
{'maximum': 300, 'minimum': 50, 'type': 'integer'},
Expand Down
17 changes: 11 additions & 6 deletions pydantic/json_schema.py
Expand Up @@ -734,12 +734,17 @@ def function_wrap_schema(self, schema: core_schema.WrapValidatorFunctionSchema)
def default_schema(self, schema: core_schema.WithDefaultSchema) -> JsonSchemaValue:
json_schema = self.generate_inner(schema['schema'])

if 'default' in schema:
default = schema['default']
elif 'default_factory' in schema:
default = schema['default_factory']()
else: # pragma: no cover
raise ValueError('`schema` has neither default nor default_factory')
if 'default' not in schema:
return json_schema
default = schema['default']
# Note: if you want to include the value returned by the default_factory,
# override this method and replace the code above with:
# if 'default' in schema:
# default = schema['default']
# elif 'default_factory' in schema:
# default = schema['default_factory']()
# else:
# return json_schema

try:
encoded_default = self.encode_default(default)
Expand Down
1 change: 0 additions & 1 deletion tests/test_dataclasses.py
Expand Up @@ -566,7 +566,6 @@ class User:
},
'aliases': {
'additionalProperties': {'type': 'string'},
'default': {'John': 'Joey'},
'title': 'Aliases',
'type': 'object',
},
Expand Down
12 changes: 12 additions & 0 deletions tests/test_json_schema.py
Expand Up @@ -4621,3 +4621,15 @@ class Model(BaseModel):
'examples': b'{"foo":{"name":"John","age":28}}',
'title': 'ModelTitle',
}


def test_inclusion_of_defaults():
class Model(BaseModel):
x: int = 1
y: int = Field(default_factory=lambda: 2)

assert Model.model_json_schema() == {
'properties': {'x': {'default': 1, 'title': 'X', 'type': 'integer'}, 'y': {'title': 'Y', 'type': 'integer'}},
'title': 'Model',
'type': 'object',
}

0 comments on commit b618dbd

Please sign in to comment.