8000 Should `round_trip=True` ignore `@computed_field` ? · Issue #7158 · pydantic/pydantic · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Should round_trip=True ignore @computed_field ? #7158

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

Closed
1 task done
jc-louis opened this issue Aug 17, 2023 · 3 comments · Fixed by pydantic/pydantic-core#934
Closed
1 task done

Should round_trip=True ignore @computed_field ? #7158

jc-louis opened this issue Aug 17, 2023 · 3 comments · Fixed by pydantic/pydantic-core#934
Assignees
Labels
bug V2 Bug related to Pydantic V2 help wanted Pull Request welcome

Comments

@jc-louis
Copy link
Contributor
jc-louis commented Aug 17, 2023

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

If I understand the round_trip=True option correctly, I think it should ignore @computed_field ? With the example bellow, using extra='forbid' makes the round trip fails.

Example Code

from typing import List

from pydantic import BaseModel, Json, computed_field, ConfigDict


class Model(BaseModel):
    json_obj: Json[List[int]]

    model_config = ConfigDict(extra='forbid')

    @computed_field
    @property
    def first(self) -> int:
        return self.json_obj[0]


dumped = Model(json_obj="[1, 2]").model_dump_json(round_trip=True)
print(dumped)
# > {"json_obj":"[1,2]","first":1}
print(Model.model_validate_json(dumped))
# pydantic_core._pydantic_core.ValidationError: 1 validation error for Model
# first
#   Extra inputs are not permitted [type=extra_forbidden, input_value=1, input_type=int]

Python, Pydantic & OS Version

pydantic version: 2.1.1
pydantic-core version: 2.4.0

Selected Assignee: @dmontagu

@jc-louis jc-louis added bug V2 Bug related to Pydantic V2 unconfirmed labels Aug 17, 2023
@samuelcolvin
Copy link
Member

Ye, I guess it should 👍.

My guess is there are a number of other changes we should make to improve round_trip, but I don't know what they are right now.

@samuelcolvin samuelcolvin added help wanted Pull Request welcome and removed unconfirmed labels Aug 22, 2023
@samuelcolvin
Copy link
Member

PR welcome to pydantic-core to skip computed_field if round_trip=True.

@scottzach1
Copy link
scottzach1 commented Aug 23, 2023

Apologies pretty low value contribution but a quick easy temporary "fix" for those affected is:

from pydantic import BaseModel, model_serializer, SerializationInfo

class RoundTripModel(BaseModel):

    @model_serializer(mode="wrap")
    def _pop_extra_fields_round_trip(self, handler, info: SerializationInfo):
        """
        Removes all computed fields to support serialize/deserialize when `round_trip=True`:
        https://github.com/pydantic/pydantic/issues/7158

        Warning: A side effect of defining a `@model_serializer` is that any raised exceptions will be translated to
        `PydanticSerializationError` by `pydantic_core`.
        """
        result = handler(self)

        if info.round_trip:
            if info.by_alias:
                excl = (f.alias or k for k, f in self.model_computed_fields.items())
            else:
                excl = self.model_computed_fields

            for key in excl:
                del result[key]

        return result

Edit 1: Fix excl behavior when alias is not defined.

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 help wanted Pull Request welcome
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants
0