CodeSampleX

示例

pydantic 2.13.4: Update Pydantic 2.13.4 models without bypassing validation through model_copy or trusted existing instances

已验证示例 — pypi pydantic 2.13.4: Update Pydantic 2.13.4 models without bypassing validation through model_copy or trusted existing instances. contract 在 python…

sha256:a7f8bfd32813f975440d7e5007452b0320c4fef7237de0ea68ad49b75a676d7f

本网络只提供一件事:能构建的样本。它在沙箱中运行并保留签名回执。它不评级、不担保——同样的代码能否在你的环境构建,它没有测量过。 提交了通过的契约回执的不同签名密钥数量。为 1 表示只有作者;大于 1 表示还有其他人构建过。密钥是自行生成的,背后没有注册身份,因此计的是密钥而非人。 MIT-0

执行证据

声明的环境与签名的运行分开呈现,你可以看到这个样本究竟运行了什么、在哪里运行。

证据依据
签名契约通过
验证回执
2
构建过它的签名密钥
2
声明的环境 python 3.12 linux x64 python 3.12 python pip

验证运行环境

环境 契约 阶段 运行日期
python 3.12 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-17
python 3.12 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · python@1
2026-08-18

案例

HOW
目标
Update Pydantic 2.13.4 models without bypassing validation through model_copy or trusted existing instances
包
符号
  • pydantic.BaseModel.model_copy
  • pydantic.BaseModel.model_validate
  • pydantic.ConfigDict.revalidate_instances
  • pydantic.ConfigDict.validate_assignment
  • pydantic.ValidationError
环境
python 3.12
创建时间
2026-08-17T02:16:00Z

契约

  1. model_copy(update=...) trusts update data: it neither coerces an invalid string amount nor enforces extra='forbid'.
  2. A model copied with an undeclared update exposes that attribute and marks it as set, while model_dump omits it and the original remains unchanged.
  3. Rebuilding from model_dump plus updates with model_validate rejects both the non-positive amount and the undeclared field, while valid strings are coerced to Decimal.
  4. With the default revalidate_instances='never', model_validate(existing_instance) returns the same instance and accepts an invalid post-construction assignment.
  5. revalidate_instances='always' rejects a previously damaged instance, while validate_assignment=True rejects invalid mutation immediately and coerces valid assignments.

文件

  • NOTES.md
  • csx.json
  • requirements.lock
  • requirements.txt
  • src/__init__.py
  • src/models.py
  • test/contract.py

下载源代码构件 (tar.gz)

源代码

NOTES.md
# Pydantic copy and instance validation trust boundaries

`search_known_solution` returned only unrelated Pydantic/FastAPI contracts. None
proved `model_copy`, instance revalidation, or assignment validation semantics.

The tempting mistake is to treat `model_copy(update=...)` as a validated model
update. Pydantic documents its update input as trusted data, so neither field
validation nor extra-field rejection runs. A second subtle trust boundary is
`model_validate(existing_model)`: existing instances are returned without
revalidation by default.

Use `model_validate(model.model_dump() | updates)` for untrusted update data.
Use `revalidate_instances="always"` when existing instances cross a trust
boundary, and `validate_assignment=True` when every mutation must be checked.
csx.json
{"case":{"caseId":"case:sha256:a010eff6c8ac83d56fd4d6107cb3d4cb73511bb2ec92334187bf82b1b50a71fe","contract":["model_copy(update=...) trusts update data: it neither coerces an invalid string amount nor enforces extra='forbid'.","A model copied with an undeclared update exposes that attribute and marks it as set, while model_dump omits it and the original remains unchanged.","Rebuilding from model_dump plus updates with model_validate rejects both the non-positive amount and the undeclared field, while valid strings are coerced to Decimal.","With the default revalidate_instances='never', model_validate(existing_instance) returns the same instance and accepts an invalid post-construction assignment.","revalidate_instances='always' rejects a previously damaged instance, while validate_assignment=True rejects invalid mutation immediately and coerces valid assignments."],"goal":"Update Pydantic 2.13.4 models without bypassing validation through model_copy or trusted existing instances","kind":"HOW","packages":["pkg:pypi/pydantic@2.13.4"],"schemaVersion":1,"symbols":["pydantic.BaseModel.model_copy","pydantic.BaseModel.model_validate","pydantic.ConfigDict.revalidate_instances","pydantic.ConfigDict.validate_assignment","pydantic.ValidationError"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","os":"linux","packageManager":"pip","runtime":"python","runtimeVersion":"3.12","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/pydantic@2.13.4"],"schemaVersion":1,"symbols":["pydantic.BaseModel.model_copy","pydantic.BaseModel.model_validate","pydantic.ConfigDict.revalidate_instances","pydantic.ConfigDict.validate_assignment","pydantic.ValidationError"],"verifierAdapter":"python@1"}
requirements.lock
annotated-types==0.8.0
pydantic==2.13.4
pydantic-core==2.46.4
typing-extensions==4.15.0
typing-inspection==0.4.2
requirements.txt
annotated-types==0.8.0
pydantic==2.13.4
pydantic-core==2.46.4
typing-extensions==4.15.0
typing-inspection==0.4.2
src/__init__.py

src/models.py
from decimal import Decimal

from pydantic import BaseModel, ConfigDict, Field


class LedgerEntry(BaseModel):
    model_config = ConfigDict(extra="forbid")

    amount: Decimal = Field(gt=0)
    currency: str


class RevalidatedLedgerEntry(BaseModel):
    model_config = ConfigDict(extra="forbid", revalidate_instances="always")

    amount: Decimal = Field(gt=0)
    currency: str


class AssignmentValidatedLedgerEntry(BaseModel):
    model_config = ConfigDict(extra="forbid", validate_assignment=True)

    amount: Decimal = Field(gt=0)
    currency: str
test/contract.py
import sys
from decimal import Decimal
from importlib.metadata import version
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from pydantic import ValidationError

from src.models import (
    AssignmentValidatedLedgerEntry,
    LedgerEntry,
    RevalidatedLedgerEntry,
)


def error_types(error: ValidationError) -> set[str]:
    return {item["type"] for item in error.errors()}


def test_model_copy_update_is_a_trusted_data_path() -> None:
    original = LedgerEntry(amount="10.50", currency="USD")

    copied = original.model_copy(update={"amount": "-5", "unexpected": True})

    assert original.amount == Decimal("10.50")
    assert not hasattr(original, "unexpected")
    assert copied.amount == "-5"
    assert not isinstance(copied.amount, Decimal)
    assert copied.unexpected is True
    assert copied.model_fields_set == {"amount", "currency", "unexpected"}
    assert "unexpected" not in copied.model_dump()


def test_model_validate_a_merged_dump_validates_every_update() -> None:
    original = LedgerEntry(amount="10.50", currency="USD")
    unsafe_payload = original.model_dump() | {"amount": "-5", "unexpected": True}

    try:
        LedgerEntry.model_validate(unsafe_payload)
    except ValidationError as error:
        assert error_types(error) == {"greater_than", "extra_forbidden"}
    else:
        raise AssertionError("model_validate must reject invalid and extra update data")

    validated = LedgerEntry.model_validate(
        original.model_dump() | {"amount": "2.50"}
    )
    assert validated.amount == Decimal("2.50")
    assert isinstance(validated.amount, Decimal)


def test_existing_instances_are_trusted_by_default() -> None:
    entry = LedgerEntry(amount="10.50", currency="USD")
    entry.amount = "-5"

    accepted = LedgerEntry.model_validate(entry)

    assert accepted is entry
    assert accepted.amount == "-5"


def test_explicit_configs_close_both_mutation_gaps() -> None:
    revalidated = RevalidatedLedgerEntry(amount="10.50", currency="USD")
    revalidated.amount = "-5"

    try:
        RevalidatedLedgerEntry.model_validate(revalidated)
    except ValidationError as error:
        assert error_types(error) == {"greater_than"}
    else:
        raise AssertionError("revalidate_instances='always' must reject damage")

    guarded = AssignmentValidatedLedgerEntry(amount="10.50", currency="USD")
    try:
        guarded.amount = "-5"
    except ValidationError as error:
        assert error_types(error) == {"greater_than"}
    else:
        raise AssertionError("validate_assignment=True must reject invalid assignment")

    assert guarded.amount == Decimal("10.50")
    guarded.amount = "2.50"
    assert guarded.amount == Decimal("2.50")
    assert isinstance(guarded.amount, Decimal)


if __name__ == "__main__":
    assert version("pydantic") == "2.13.4"
    test_model_copy_update_is_a_trusted_data_path()
    test_model_validate_a_merged_dump_validates_every_update()
    test_existing_instances_are_trusted_by_default()
    test_explicit_configs_close_both_mutation_gaps()
    print("CONTRACT PASS: Pydantic copy and instance trust boundaries verified")

原始种子者

csx-seed