Skip to content

computed_fields have inconsistent behaviour between model_dump and model_dump_json #8250

@Samreay

Description

@Samreay

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

There seems to be inconsistent behaviour between model_dump and model_dump_json with computed fields.

Example Code

from pydantic import BaseModel, computed_field


class Example(BaseModel):
    x: int
    y: int | None

    @computed_field
    def computed(self) -> None:
        return None


if __name__ == "__main__":
    e = Example(x=1, y=None)

    print(e.model_dump(exclude_none=True))
    # {'x': 1}

    print(e.model_dump_json(exclude_none=True))
    # {"x":1,"computed":null}

Python, Pydantic & OS Version

pydantic version: 2.5.2
        pydantic-core version: 2.14.5
          pydantic-core build: profile=release pgo=true
                 install path: /home/sam/arenko/trade-selector/.venv/lib/python3.11/site-packages/pydantic
               python version: 3.11.4 (main, Jul  4 2023, 13:46:25) [GCC 11.3.0]
                     platform: Linux-5.15.133.1-microsoft-standard-WSL2-x86_64-with-glibc2.35
             related packages: fastapi-0.104.1 typing_extensions-4.8.0 mypy-1.7.0 pydantic-settings-2.1.0

Metadata

Metadata

Assignees

Labels

bug V2Bug related to Pydantic V2

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions