Skip to content

model_dump(exclude_defaults=True) fails for numpy fields due to failed equality checks #7307

@coltonbh

Description

@coltonbh

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

When I include arbitrary types, like a numpy ndarray, and try to run .model_dump(exclude_defaults=True) the call fails due to an inability to perform equality checks that work with numpy.

Is there a solution for this I'm missing? Perhaps some way to specify __eq__ checks for a field? I'm guessing under the hood pydantic is checking if the field value is set to the default with a == check, which fails for numpy.

Exception:

Traceback (most recent call last):
  File "/home/cbh/dev/hacking/pydantic/example.py", line 26, in <module>
    dumped3 = model.model_dump(exclude_defaults=True)  # Fails!
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/cbh/dev/hacking/pydantic/env/lib/python3.11/site-packages/pydantic/main.py", line 309, in model_dump
    return self.__pydantic_serializer__.to_python(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Example Code

from typing import Optional

from numpy import ndarray
from typing_extensions import Annotated
from pydantic import BaseModel, PlainSerializer


NumpyArray = Annotated[ndarray, PlainSerializer(lambda x: x.tolist())]


class MyModel(BaseModel):
    foo: str
    bar: NumpyArray = ndarray([])
    baz: Optional[int] = None

    model_config = {"arbitrary_types_allowed": True}


if __name__ == "__main__":
    model = MyModel(foo="hello", bar=ndarray([1, 2, 3]))

    dumped1 = model.model_dump()  # Works!
    dumped2 = model.model_dump(exclude_none=True)  # Works!
    assert "baz" not in dumped2
    assert "bar" in dumped2

    dumped3 = model.model_dump(exclude_defaults=True)  # Fails!

Python, Pydantic & OS Version

pydantic version: 2.3.0
        pydantic-core version: 2.6.3
          pydantic-core build: profile=release pgo=true
                 install path: /home/cbh/dev/hacking/pydantic/env/lib/python3.11/site-packages/pydantic
               python version: 3.11.5 (main, Aug 31 2023, 10:50:44) [GCC 11.4.0]
                     platform: Linux-5.19.0-41-generic-x86_64-with-glibc2.35
     optional deps. installed: ['typing-extensions']

Selected Assignee: @davidhewitt

Metadata

Metadata

Assignees

Labels

bug V2Bug related to Pydantic V2pendingIs unconfirmed

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions