5.4. Combining Pydantic and semver

According to its homepage, Pydantic “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 Version first and add the magic methods __get_validators__() and __modify_schema__() like this:

    from semver import Version
    class PydanticVersion(Version):
        def _parse(cls, version):
            return cls.parse(version)
        def __get_validators__(cls):
            """Return a list of validator methods for pydantic models."""
            yield cls._parse
        def __modify_schema__(cls, field_schema):
            """Inject/mutate the pydantic field schema in-place."""
  2. Create a new model (in this example MyModel) and derive it from pydantic.BaseModel:

    import pydantic
    class MyModel(pydantic.BaseModel):
        version: PydanticVersion
  3. Use your model like this:

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

    The attribute model.version will be an instance of Version. If the version is invalid, the construction will raise a pydantic.ValidationError.