Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Describe Pydantic and semver in "Advanced topics" #353

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

Merged
merged 1 commit into from
Jan 28, 2022
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions changelog.d/343.doc.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Describe combining Pydantic with semver in the "Advanced topic"
section.
53 changes: 53 additions & 0 deletions docs/advanced/combine-pydantic-and-semver.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
Combining Pydantic and semver
=============================

According to its homepage, `Pydantic <https://pydantic-docs.helpmanual.io>`_
"enforces type hints at runtime, and provides user friendly errors when data
is invalid."

To work with Pydantic, use the following steps:


1. Derive a new class from :class:`~semver.version.Version`
first and add the magic methods :py:meth:`__get_validators__`
and :py:meth:`__modify_schema__` like this:

.. code-block:: python

from semver import Version

class PydanticVersion(Version):
@classmethod
def __get_validators__(cls):
"""Return a list of validator methods for pydantic models."""
yield cls.parse

@classmethod
def __modify_schema__(cls, field_schema):
"""Inject/mutate the pydantic field schema in-place."""
field_schema.update(examples=["1.0.2",
"2.15.3-alpha",
"21.3.15-beta+12345",
]
)

2. Create a new model (in this example :class:`MyModel`) and derive
it from :class:`pydantic.BaseModel`:

.. code-block:: python

import pydantic

class MyModel(pydantic.BaseModel):
version: PydanticVersion

3. Use your model like this:

.. code-block:: python

model = MyModel.parse_obj({"version": "1.2.3"})

The attribute :py:attr:`model.version` will be an instance of
:class:`~semver.version.Version`.
If the version is invalid, the construction will raise a
:py:exc:`pydantic.ValidationError`.
4 changes: 2 additions & 2 deletions docs/advanced/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ Advanced topics
===============



.. toctree::

deal-with-invalid-versions
create-subclasses-from-version
display-deprecation-warnings
display-deprecation-warnings
combine-pydantic-and-semver