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

clean Model docstrings in JSON Schema #7210

Merged
merged 2 commits into from Aug 23, 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/usage/json_schema.md
Expand Up @@ -95,7 +95,7 @@ print(json.dumps(MainModel.model_json_schema(), indent=2))
"type": "string"
}
},
"description": "\n This is the description of the main model\n ",
"description": "This is the description of the main model",
"properties": {
"foo_bar": {
"$ref": "#/$defs/FooBar"
Expand Down
2 changes: 1 addition & 1 deletion pydantic/_internal/_generate_schema.py
Expand Up @@ -219,7 +219,7 @@ def modify_model_json_schema(
original_schema['title'] = cls.__name__
docstring = cls.__doc__
if docstring and 'description' not in original_schema:
original_schema['description'] = docstring
original_schema['description'] = inspect.cleandoc(docstring)
return json_schema


Expand Down
19 changes: 19 additions & 0 deletions tests/test_json_schema.py
Expand Up @@ -1695,6 +1695,25 @@ class B(A):
assert B.model_json_schema() == {'title': 'B', 'type': 'object', 'properties': {}}


@pytest.mark.parametrize(
'docstring,description',
[
('foobar', 'foobar'),
('\n foobar\n ', 'foobar'),
('foobar\n ', 'foobar\n '),
('foo\n bar\n ', 'foo\nbar'),
('\n foo\n bar\n ', 'foo\nbar'),
],
)
def test_docstring(docstring, description):
class A(BaseModel):
x: int

A.__doc__ = docstring

assert A.model_json_schema()['description'] == description


@pytest.mark.parametrize(
'kwargs,type_,expected_extra',
[
Expand Down