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:
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): @classmethod def _parse(cls, version): return cls.parse(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", ] )
Create a new model (in this example
MyModel
) and derive it frompydantic.BaseModel
:import pydantic class MyModel(pydantic.BaseModel): version: PydanticVersion
Use your model like this:
model = MyModel.parse_obj({"version": "1.2.3"})
The attribute
model.version
will be an instance ofVersion
. If the version is invalid, the construction will raise apydantic.ValidationError
.