-
-
Notifications
You must be signed in to change notification settings - Fork 205
Support defaults from Pydantic fields #802
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
Draft
jinnovation
wants to merge
33
commits into
mitmproxy:main
Choose a base branch
from
jinnovation:pydantic
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
33 commits
Select commit
Hold shift + click to select a range
9dcfd25
Support defaults from Pydantic fields
jinnovation 991910c
gate specifically on pydantic
jinnovation b077891
do not include importerror block in test coverage
jinnovation 19efc29
extend pragma no cover
jinnovation 7a32d2b
WIP: Convert to snapshot test
jinnovation a413dd9
remove dataclass import
jinnovation 25090dd
create _pydantic module
jinnovation bad5751
Merge remote-tracking branch 'upstream/main' into pydantic
jinnovation a2ab163
[autofix.ci] apply automated fixes
autofix-ci[bot] 83f467c
fix lint
jinnovation 5381116
fix importlib import
jinnovation adbe853
mark generated files
jinnovation 10c35b8
suppress BaseModel fields
jinnovation 3206e0f
harden
jinnovation 9f9e5d6
update snapshot
jinnovation 236e97d
add note
jinnovation b576d73
changelog
jinnovation db7938d
[autofix.ci] apply automated fixes
autofix-ci[bot] 5d44d35
Merge remote-tracking branch 'upstream/main' into pydantic
jinnovation cdee9e5
add docs
jinnovation 010d26b
[autofix.ci] apply automated fixes
autofix-ci[bot] 5182cd0
Merge branch 'main' into pydantic
jinnovation ee2a783
undo gitattributes
jinnovation 3f26ff7
Update pdoc/__init__.py
jinnovation fb31c98
render docstring
jinnovation 9327e13
[autofix.ci] apply automated fixes
autofix-ci[bot] 1795c40
_pydantic.skip_field
jinnovation 9a19f6e
[autofix.ci] apply automated fixes
autofix-ci[bot] 82d54fe
fix lint
jinnovation 976c236
refining pydantic-installed detection logic
jinnovation 3506b48
fix lint
jinnovation cd271f2
support 3.9 type checking
jinnovation 5fd7462
expand type annotations
jinnovation File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,97 @@ | ||
"""Work with Pydantic models.""" | ||
|
||
from importlib import import_module | ||
from types import ModuleType | ||
from typing import TYPE_CHECKING | ||
from typing import Any | ||
from typing import Final | ||
from typing import Optional | ||
from typing import TypeVar | ||
from typing import cast | ||
|
||
from pdoc.docstrings import AnyException | ||
|
||
if TYPE_CHECKING: | ||
import pydantic | ||
else: | ||
pydantic: Optional[ModuleType] | ||
try: | ||
pydantic = import_module("pydantic") | ||
except AnyException: | ||
pydantic = None | ||
|
||
|
||
_IGNORED_FIELDS: Final[list[str]] = ["__fields__"] | ||
"""Fields to ignore when generating docs, e.g. those that emit deprecation warnings.""" | ||
|
||
T = TypeVar("T") | ||
|
||
|
||
def is_pydantic_model(obj: Any) -> bool: | ||
"""Returns whether an object is a Pydantic model. | ||
|
||
Raises: | ||
ModuleNotFoundError: when function is called but Pydantic is not on the PYTHONPATH. | ||
|
||
""" | ||
if pydantic is None: | ||
raise ModuleNotFoundError( | ||
"_pydantic.is_pydantic_model() needs Pydantic installed" | ||
) | ||
|
||
return pydantic.BaseModel in obj.__bases__ | ||
|
||
|
||
def default_value(parent: Any, name: str, obj: T) -> T: | ||
"""Determine the default value of obj. | ||
|
||
If pydantic is not installed or the parent type is not a Pydantic model, | ||
simply returns obj. | ||
|
||
""" | ||
if ( | ||
pydantic is not None | ||
and isinstance(parent, type) | ||
and issubclass(parent, pydantic.BaseModel) | ||
): | ||
_parent = cast(pydantic.BaseModel, parent) | ||
pydantic_fields = _parent.__pydantic_fields__ | ||
return pydantic_fields[name].default if name in pydantic_fields else obj | ||
|
||
return obj | ||
|
||
|
||
def get_field_docstring(parent: Any, field_name: str) -> Optional[str]: | ||
if ( | ||
pydantic is not None | ||
and isinstance(parent, type) | ||
and issubclass(parent, pydantic.BaseModel) | ||
): | ||
pydantic_fields = parent.__pydantic_fields__ | ||
return ( | ||
pydantic_fields[field_name].description | ||
if field_name in pydantic_fields | ||
else None | ||
) | ||
|
||
return None | ||
|
||
|
||
def skip_field( | ||
*, | ||
parent_kind: str, | ||
parent_obj: Any, | ||
name: str, | ||
taken_from: tuple[str, str], | ||
) -> bool: | ||
"""For Pydantic models, filter out all methods on the BaseModel | ||
class, as they are almost never relevant to the consumers of the | ||
inheriting model itself. | ||
""" | ||
|
||
return ( | ||
pydantic is not None | ||
and parent_kind == "class" | ||
and is_pydantic_model(parent_obj) | ||
and (name in _IGNORED_FIELDS or taken_from[0].startswith("pydantic")) | ||
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -44,6 +44,7 @@ | |
from typing import get_origin | ||
import warnings | ||
|
||
from pdoc import _pydantic | ||
from pdoc import doc_ast | ||
from pdoc import doc_pyi | ||
from pdoc import extract | ||
|
@@ -257,6 +258,15 @@ def members(self) -> dict[str, Doc]: | |
for name, obj in self._member_objects.items(): | ||
qualname = f"{self.qualname}.{name}".lstrip(".") | ||
taken_from = self._taken_from(name, obj) | ||
|
||
if _pydantic.skip_field( | ||
parent_kind=self.kind, | ||
parent_obj=self.obj, | ||
name=name, | ||
taken_from=taken_from, | ||
): | ||
continue | ||
|
||
doc: Doc[Any] | ||
|
||
is_classmethod = isinstance(obj, classmethod) | ||
|
@@ -314,18 +324,35 @@ def members(self) -> dict[str, Doc]: | |
taken_from=taken_from, | ||
) | ||
else: | ||
default_value = obj | ||
|
||
default_value = _pydantic.default_value(self.obj, name, obj) | ||
|
||
doc = Variable( | ||
self.modulename, | ||
qualname, | ||
docstring="", | ||
annotation=self._var_annotations.get(name, empty), | ||
default_value=obj, | ||
default_value=default_value, | ||
taken_from=taken_from, | ||
) | ||
if self._var_docstrings.get(name): | ||
doc.docstring = self._var_docstrings[name] | ||
if self._func_docstrings.get(name) and not doc.docstring: | ||
doc.docstring = self._func_docstrings[name] | ||
|
||
_docstring: str | None = None | ||
if ( | ||
_pydantic.pydantic is not None | ||
and self.kind == "class" | ||
and _pydantic.is_pydantic_model(self.obj) | ||
): | ||
_docstring = _pydantic.get_field_docstring(self.obj, name) | ||
Comment on lines
+341
to
+346
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Consolidate conditional logic into |
||
|
||
if _docstring is None: | ||
if self._var_docstrings.get(name): | ||
doc.docstring = self._var_docstrings[name] | ||
if self._func_docstrings.get(name) and not doc.docstring: | ||
doc.docstring = self._func_docstrings[name] | ||
else: | ||
doc.docstring = _docstring | ||
|
||
members[doc.name] = doc | ||
|
||
if isinstance(self, Module): | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
""" | ||
A small example with Pydantic entities. | ||
""" | ||
|
||
import pydantic | ||
|
||
|
||
class Foo(pydantic.BaseModel): | ||
"""Foo class documentation.""" | ||
|
||
model_config = pydantic.ConfigDict( | ||
use_attribute_docstrings=True, | ||
) | ||
|
||
a: int = pydantic.Field(default=1, description="Docstring for a") | ||
|
||
b: int = 2 | ||
"""Docstring for b.""" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
<module with_pydantic # A small example with… | ||
<class with_pydantic.Foo # Foo class documentat… | ||
<var model_config = {'use_attribute_docstrings': True} # Configuration for th…> | ||
<var a: int = 1 # Docstring for a> | ||
<var b: int = 2 # Docstring for b.> | ||
> | ||
> |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.