Skip to content

Commit bafd212

Browse files
authored
Merge pull request #353 from tomschr/feature/343-pydantic-into-doc
Describe Pydantic and semver in "Advanced topics"
2 parents 53f721a + 73bd190 commit bafd212

File tree

3 files changed

+57
-2
lines changed

3 files changed

+57
-2
lines changed

changelog.d/343.doc.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Describe combining Pydantic with semver in the "Advanced topic"
2+
section.
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
Combining Pydantic and semver
2+
=============================
3+
4+
According to its homepage, `Pydantic <https://pydantic-docs.helpmanual.io>`_
5+
"enforces type hints at runtime, and provides user friendly errors when data
6+
is invalid."
7+
8+
To work with Pydantic, use the following steps:
9+
10+
11+
1. Derive a new class from :class:`~semver.version.Version`
12+
first and add the magic methods :py:meth:`__get_validators__`
13+
and :py:meth:`__modify_schema__` like this:
14+
15+
.. code-block:: python
16+
17+
from semver import Version
18+
19+
class PydanticVersion(Version):
20+
@classmethod
21+
def __get_validators__(cls):
22+
"""Return a list of validator methods for pydantic models."""
23+
yield cls.parse
24+
25+
@classmethod
26+
def __modify_schema__(cls, field_schema):
27+
"""Inject/mutate the pydantic field schema in-place."""
28+
field_schema.update(examples=["1.0.2",
29+
"2.15.3-alpha",
30+
"21.3.15-beta+12345",
31+
]
32+
)
33+
34+
2. Create a new model (in this example :class:`MyModel`) and derive
35+
it from :class:`pydantic.BaseModel`:
36+
37+
.. code-block:: python
38+
39+
import pydantic
40+
41+
class MyModel(pydantic.BaseModel):
42+
version: PydanticVersion
43+
44+
3. Use your model like this:
45+
46+
.. code-block:: python
47+
48+
model = MyModel.parse_obj({"version": "1.2.3"})
49+
50+
The attribute :py:attr:`model.version` will be an instance of
51+
:class:`~semver.version.Version`.
52+
If the version is invalid, the construction will raise a
53+
:py:exc:`pydantic.ValidationError`.

docs/advanced/index.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@ Advanced topics
22
===============
33

44

5-
65
.. toctree::
76

87
deal-with-invalid-versions
98
create-subclasses-from-version
10-
display-deprecation-warnings
9+
display-deprecation-warnings
10+
combine-pydantic-and-semver

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy