Skip to content

Commit

Permalink
clean Model docstrings in JSON Schema (#7210)
Browse files Browse the repository at this point in the history
  • Loading branch information
samuelcolvin committed Aug 23, 2023
1 parent bd2b524 commit d110b47
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
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

0 comments on commit d110b47

Please sign in to comment.