You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When trying to exclude subfields fields in model_dump_json on a model with fields defined as Sequence[something], serialization fails with "Error calling function serialize_sequence_via_list: ValueError: Negative indices cannot be used to exclude items on unsized iterables".
The serialization works fine when using list[something] instead of Sequence[something], but when using this mypy forbids to override with list[subclass of something] in subclasses of the model.
This was working fine with Sequence until updating from Pydantic 2.6.x to 2.7.1.
Example Code
fromtypingimportSequencefrompydanticimportBaseModelexclude= {"releases": {"__all__": {"build": True}}}
classRelease(BaseModel):
version: strname: strdesc: strclassBundleSeq(BaseModel):
releases: Sequence[Release]
classBundleList(BaseModel):
releases: list[Release]
r1=Release(name="Foo", version="1.0", desc="Foo v1.0")
r2=Release(name="Bar", version="2.0", desc="Bar v2.0")
b1=BundleSeq(releases=[r1, r2])
b2=BundleList(releases=[r1, r2])
try:
print(b1.model_dump_json(exclude=exclude))
exceptExceptionase:
print(e)
print(b2.model_dump_json(exclude=exclude))
# Output:# Error serializing to JSON: PydanticSerializationError: Error calling function `serialize_sequence_via_list`: ValueError: Negative indices cannot be used to exclude items on unsized iterables# {"releases":[{"version":"1.0","name":"Foo","desc":"Foo v1.0"},{"version":"2.0","name":"Bar","desc":"Bar v2.0"}]}## Expected output:# {"releases":[{"version":"1.0","name":"Foo","desc":"Foo v1.0"},{"version":"2.0","name":"Bar","desc":"Bar v2.0"}]}# {"releases":[{"version":"1.0","name":"Foo","desc":"Foo v1.0"},{"version":"2.0","name":"Bar","desc":"Bar v2.0"}]}
Thanks for reporting this. Will work on a fix for 2.7.2! We did do some sequence validation modification from 2.6 -> 2.7, so I'm not surprised that there were some problems.
Initial Checks
Description
When trying to exclude subfields fields in model_dump_json on a model with fields defined as Sequence[something], serialization fails with "Error calling function
serialize_sequence_via_list
: ValueError: Negative indices cannot be used to exclude items on unsized iterables".Types matching the Sequence generic type have a length and accepts negative indices according to Python doc: https://docs.python.org/3/library/stdtypes.html#sequence-types-list-tuple-range
The serialization works fine when using list[something] instead of Sequence[something], but when using this mypy forbids to override with list[subclass of something] in subclasses of the model.
This was working fine with Sequence until updating from Pydantic 2.6.x to 2.7.1.
Example Code
Python, Pydantic & OS Version
The text was updated successfully, but these errors were encountered: