Skip to content

Support exclude_if for computed fields #12690

@joshorr

Description

@joshorr

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

The new exclude_if annotation in Field is ignored on computed_fields.

I am not sure if this is similar to or completely different from the other issue (#12387). It seems like it's different enough I decided to open a new issue.

Example Code

from pydantic import BaseModel, Field
from typing import Annotated

IntExcludeZero = Annotated[int, Field(exclude_if=lambda v: v == 0)]

class Model(BaseModel):
    @computed_field
    def a_computed_field(self) -> IntExcludeZero:
        return 0

obj = Model()
print(obj.model_dump())  # {"a_computed_field": 0 }

The expected behavior for the code above is for a_computed_field to not be in the result due to the exclude_if directive.

Python, Pydantic & OS Version

             pydantic version: 2.12.5
        pydantic-core version: 2.41.5
          pydantic-core build: profile=release pgo=false
               python version: 3.10.14 (main, Nov  9 2024, 11:48:33) [Clang 16.0.0 (clang-1600.0.26.4)]
                     platform: macOS-15.7.3-arm64-arm-64bit
             related packages: mypy-1.19.1 typing_extensions-4.15.0
                       commit: unknown

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions