-
Notifications
You must be signed in to change notification settings - Fork 71
Open
Description
CloudPath's are supported in Pydantic BaseModel's but when you try to serialize them I get a PydanticSerializationError: Unable to serialize unknown type.
I think it would be an easy fix to add. Note that Path serialization is supported.
Reproducible code snippet:
from pydantic import BaseModel
from cloudpathlib import CloudPath
class SomeModel(BaseModel):
field_a: CloudPath
SomeModel(field_a="s3://bucket/key").model_dump_json()Fix required, in the below function add a serialization parameter to no_info_after_validator_function:
cloudpathlib/cloudpathlib/cloudpath.py
Lines 1587 to 1598 in 28f1d94
| def __get_pydantic_core_schema__(cls, _source_type: Any, _handler): | |
| """Pydantic special method. See | |
| https://docs.pydantic.dev/2.0/usage/types/custom/""" | |
| try: | |
| from pydantic_core import core_schema | |
| return core_schema.no_info_after_validator_function( | |
| cls.validate, | |
| core_schema.any_schema(), | |
| ) | |
| except ImportError: | |
| return None |
i.e.
return core_schema.no_info_after_validator_function(
cls.validate,
core_schema.any_schema(),
serialization=core_schema.plain_serializer_function_ser_schema(
lambda x: str(x),
return_schema=core_schema.str_schema(),
),
)Easy workaround for now is to add a PlainSerializer:
from pydantic import PlainSerializer, BaseModel
from cloudpathlib import CloudPath
from typing import Annotated
class SomeModel(BaseModel):
field_a: Annotated[CloudPath, PlainSerializer(lambda x: str(x))]
SomeModel(field_a="s3://bucket/key").model_dump_json()Let me know if you agree with adding this. Only just started using the library but I think it's a pretty easy fix so can probably help contribute.
Metadata
Metadata
Assignees
Labels
No labels