|
| 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`. |
0 commit comments