Complete worked example
python
from pydantic import BaseModel, SecretStr, ValidationError
class PublicUser(BaseModel):
name: str
nickname: str | None = None
class PrivateUser(PublicUser):
password: SecretStr
class Envelope(BaseModel):
user: PublicUser
def inspect_example(payload):
try:
private = PrivateUser.model_validate(payload)
envelope = Envelope(user=private)
return {"value": envelope.model_dump(mode="json")}
except ValidationError as error:
return {"error": sorted({e["type"] for e in error.errors()})}- Reasoning
- Pydantic validates the synthetic private input, then serializes the envelope in JSON mode using the declared public field type. The password does not appear in the expected response. A defaulted nickname appears as null unless a separate output option removes None values. The fixture compares exact keys, including the absence of the password key. SecretStr provides masked ordinary representations, but the underlying value still exists and can be retrieved deliberately. Masking is not encryption, secure storage or a substitute for selecting public fields. The lab uses fictional values only and never authenticates an external service.