Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

computed_fields have inconsistent behaviour between model_dump and model_dump_json #8250

Closed
1 task done
Samreay opened this issue Nov 29, 2023 · 3 comments · Fixed by pydantic/pydantic-core#1098
Closed
1 task done
Assignees
Labels
bug V2 Bug related to Pydantic V2
Milestone

Comments

@Samreay
Copy link

Samreay commented Nov 29, 2023

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
@Samreay Samreay added bug V2 Bug related to Pydantic V2 pending Awaiting a response / confirmation labels Nov 29, 2023
@Samreay
Copy link
Author

Samreay commented Nov 29, 2023

I believe this may be related to #5827, however I am unsure if under the hood the explicit exclude is tied to exclude_none or if there's a different handler.

@sydney-runkle sydney-runkle removed the pending Awaiting a response / confirmation label Nov 29, 2023
@sydney-runkle
Copy link
Member

@Samreay,

Thanks for reporting this. This does look like a bug 🐛. I'm adding this to our 2.6.0 milestone, and will mark with help wanted for now, if anyone wants to pick this fix up!

@sydney-runkle
Copy link
Member

Found a fix for this in pydantic-core, will have a PR up shortly. This should be fixed in our next minor release 👍.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug V2 Bug related to Pydantic V2
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants