← 输入框|github.com|刷新
Skip to content

Update "5.4. Combining Pydantic and semver" documentation to Pydantic v2.0 #422

Closed

Description

@RobinGroundfog

Situation

The documentation illustrates how to combine Pydantic with semver in this page: https://python-semver.readthedocs.io/en/latest/advanced/combine-pydantic-and-semver.html. Pydantic has since been updated to v2 and the solution presented in the documentation is not working anymore.

Possible Solution/Idea

Based on the Pydantic docs on how to work with third-party types: https://docs.pydantic.dev/latest/usage/types/custom/#handling-third-party-types

The following code is working with Pydantic>2.0

from typing import Annotated, Any, Callable
from pydantic import GetJsonSchemaHandler
from pydantic_core import core_schema
from pydantic.json_schema import JsonSchemaValue
from semver import Version


class _VersionPydanticAnnotation:
    @classmethod
    def __get_pydantic_core_schema__(
        cls,
        _source_type: Any,
        _handler: Callable[[Any], core_schema.CoreSchema],
    ) -> core_schema.CoreSchema:
        def validate_from_str(value: str) -> Version:
            return Version.parse(value)

        from_str_schema = core_schema.chain_schema(
            [
                core_schema.str_schema(),
                core_schema.no_info_plain_validator_function(validate_from_str),
            ]
        )

        return core_schema.json_or_python_schema(
            json_schema=from_str_schema,
            python_schema=core_schema.union_schema(
                [
                    core_schema.is_instance_schema(Version),
                    from_str_schema,
                ]
            ),
            serialization=core_schema.plain_serializer_function_ser_schema(
                lambda instance: instance.x
            ),
        )

    @classmethod
    def __get_pydantic_json_schema__(
        cls, _core_schema: core_schema.CoreSchema, handler: GetJsonSchemaHandler
    ) -> JsonSchemaValue:
        return handler(core_schema.str_schema())


ManifestVersion = Annotated[Version, _VersionPydanticAnnotation]

I would suggest on updating the documentation with this new code.

Activity

  1. changed the title [-]Update "5.4. Combining Pydantic and semver" to Pydantic v2.0[/-] [+]Update "5.4. Combining Pydantic and semver" documentation to Pydantic v2.0[/+] on Jul 27, 2023
  2. added a commit that references this issue on Jul 27, 2023
    2ae1a21
  3. added a commit that references this issue on Sep 16, 2023
    757ada6
  4. jaysoffian commented on Mar 1, 2024

    @jaysoffian

    This also works:

    from typing import Annotated
    from pydantic import AfterValidator, PlainSerializer
    from semver import Version
    
    PinVersion = Annotated[
        str,
        AfterValidator(Version.parse),
        # May omit the following if serialization isn't needed:
        PlainSerializer(lambda v: str(v)), 
    ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    SIze

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions