Ejemplo
pydantic 2.13.4: Replace pydantic v1 parse_obj/dict with the v2 model_validate/model_dump API
Muestra verificada para pypi pydantic 2.13.4: Replace pydantic v1 parse_obj/dict with the v2 model_validate/model_dump API. El contrato se ejecutó en python…
sha256:3ea42df47255426affc822fffa2fe475b71a881239b1db84e637d566bf47ae93
Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido.
Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas.
MIT-0
Evidencia de ejecución
El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.
- Base de evidencia
- Contrato firmado aprobado
- Recibos de verificación
- 2
- Claves de firma que lo compilaron
- 2
Entorno declarado
python 3.12 linux x64 python 3.12 python pip
Entornos de las ejecuciones de verificación
| Entorno | Contrato | Etapas | Ejecución |
|---|---|---|---|
| python 3.12 · linux alpine/x64 · docker ed25519:a2ec939a4c60e243 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · python@1 |
2026-08-13 |
| 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 |
Caso
MIGRATION- Objetivo
- Replace pydantic v1 parse_obj/dict with the v2 model_validate/model_dump API
- Paquetes
- Símbolos
-
- BaseModel.model_validate
- BaseModel.model_dump
- ValidationError
- Entorno
- python 3.12
- Creado
- 2026-08-13T15:47:11Z
Contrato
- define a model and validate a correct payload with model_validate
- assert the v1 helpers still exist but warn, so a silent upgrade is not a completed migration
- assert an invalid payload raises ValidationError with a typed error list
- assert model_dump returns plain data
Archivos
- csx.json
- requirements.txt
- src/__init__.py
- src/models.py
- test/contract.py
Código fuente
{"case":{"caseId":"case:sha256:847c47b53bfbe275a04f1c89c11fee352a20506a7c25dda57382f37eb96875a4","constraints":{"runtime":"python"},"contract":["define a model and validate a correct payload with model_validate","assert the v1 helpers still exist but warn, so a silent upgrade is not a completed migration","assert an invalid payload raises ValidationError with a typed error list","assert model_dump returns plain data"],"goal":"Replace pydantic v1 parse_obj/dict with the v2 model_validate/model_dump API","kind":"MIGRATION","packages":["pkg:pypi/pydantic@2.13.4"],"schemaVersion":1,"symbols":["BaseModel.model_validate","BaseModel.model_dump","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":["BaseModel.model_validate","BaseModel.model_dump","ValidationError"],"verifierAdapter":"python@1"}
pydantic==2.13.4
pydantic-core==2.46.4
typing-extensions==4.16.0
annotated-types==0.8.0
typing-inspection==0.4.4
"""pydantic v2 validation, with the v1 names that no longer exist."""
from pydantic import BaseModel, Field, ValidationError
class Peer(BaseModel):
peer_id: str = Field(min_length=3)
port: int = Field(ge=1, le=65535)
tags: list[str] = []
def validate(payload):
"""Validate a dict into a Peer.
v2 renamed the whole surface: parse_obj -> model_validate,
parse_raw -> model_validate_json, .dict() -> .model_dump(),
.json() -> .model_dump_json(). The old names still resolve as
deprecated shims, so a v1 codebase keeps running after the upgrade and
the migration looks finished when it is not — the warnings are the
only signal, and they are easy to filter away.
"""
return Peer.model_validate(payload)
def errors_for(payload):
"""Return the structured error list for an invalid payload."""
try:
Peer.model_validate(payload)
except ValidationError as exc:
return exc.errors()
return []
import os
import sys
import warnings
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from src.models import Peer, errors_for, validate
peer = validate({"peer_id": "ed25519:abc", "port": 48620, "tags": ["blob"]})
assert peer.peer_id == "ed25519:abc"
assert peer.port == 48620
# v2 returns plain data from model_dump; .dict() is gone.
assert validate({"peer_id": "abc", "port": 1}).model_dump() == {
"peer_id": "abc", "port": 1, "tags": []
}
# The v1 names still EXIST in v2 as deprecated shims — they do not raise
# AttributeError, they warn. That is why a v1 codebase keeps working after
# the upgrade while quietly accruing deprecation debt, and why "it still
# runs" is not evidence that the migration is done.
with warnings.catch_warnings(record=True) as caught:
warnings.simplefilter("always")
legacy = Peer.parse_obj({"peer_id": "ed25519:ghi", "port": 2})
assert legacy.port == 2
assert any(issubclass(w.category, DeprecationWarning) for w in caught), "parse_obj should warn in v2"
errs = errors_for({"peer_id": "ab", "port": 99999})
codes = sorted(e["type"] for e in errs)
assert len(errs) == 2, errs
assert all("loc" in e and "msg" in e for e in errs)
assert codes == ["less_than_equal", "string_too_short"], codes
print("CONTRACT PASS: pydantic v2 validated, dumped and reported typed errors")