-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Description
Note - the serialize_as_any runtime flag support will be released with 2.7, so this will need to be addressed once those changes are merged (see pydantic/pydantic-core#1194 and #8830)
Specifically, there are differences in regards to when serialization warnings are raised. For example:
The following test fails with warnings for passing str where int expected:
def test_serialize_as_any_list_types() -> None:
serializer = SchemaSerializer(core_schema.list_schema(core_schema.int_schema()))
assert serializer.to_python(['a', 'b', 'c'], serialize_as_any=True) == ['a', 'b', 'c']The annotated code which is equivalent doesn't warn:
from pydantic import TypeAdapter, SerializeAsAny
TypeAdapter(SerializeAsAny[list[int]]).dump_python(["a", "b", "c"])Ultimately, it'd be difficult to make the annotation behave more strictly here, given that it transforms the schema it wraps into an Any schema, which is quite permissive. Thus, in order to reconcile these differences, it probably makes the most sense for us to make the runtime flag more permissive.
One potential workaround that we considered was having the runtime flag named duck_type_serialization, but we ended up deciding not to go with this approach, as it's confusing for users to have "duck type serialization" and "serialize as any" as separate concepts. See this comment and surrounding comments for more detail.