Skip to content
Sarj Code Standards

no-invalid-pydantic-bypass

Do not create a provably invalid model through Pydantic validation bypass APIs.

Why

model_construct and model_copy(update=...) store supplied values without validation. A contradictory literal or an omitted required construction field can therefore invalidate a model's declared type while the permissive bypass signatures still pass static checking. Unpacked construction inputs and nonliteral copy updates warrant review because their field values are unknown at the bypass call.

Fix

Supply values satisfying the model contract and every required field, or validate a complete input mapping with the normal constructor or model_validate. A model_validate call on an existing model instance does not necessarily revalidate it; keep trusted bypasses only when their inputs preserve the contract.

Examples

Before — flagged Unchecked list elements must satisfy the stored field type
app/models.py
from pydantic import BaseModel
class Payload(BaseModel):
labels: list[str]
payload = Payload.model_construct(labels=[3])
After — preferred Trusted list elements preserve the field contract
app/models.py
from pydantic import BaseModel
class Payload(BaseModel):
labels: list[str]
payload = Payload.model_construct(labels=["ready"])
Before — flagged Unchecked construction stores a tag outside the declared vocabulary
app/models.py
from typing import Literal
from pydantic import BaseModel
class Job(BaseModel):
kind: Literal["queued", "done"]
job = Job.model_construct(kind="unknown")
After — preferred Trusted construction still satisfies the declared vocabulary
app/models.py
from typing import Literal
from pydantic import BaseModel
class Job(BaseModel):
kind: Literal["queued", "done"]
job = Job.model_construct(kind="queued")
Before — flagged A settings type does not validate unchecked construction
app/settings.py
from typing import Literal
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
environment: Literal["dev", "prod"]
settings = Settings.model_construct(environment="other")
After — preferred Construct the validated settings object at startup
app/settings.py
from typing import Literal
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
environment: Literal["dev", "prod"]
settings = Settings()
Before — flagged Unpacked construction and opaque copy updates bypass validation
app/models.py
from pydantic import BaseModel
class Job(BaseModel):
name: str
job = Job.model_construct(**row)
updated = Job(name="draft").model_copy(update=changes)
After — preferred Validate the complete mapping before storing field values
app/models.py
from pydantic import BaseModel
class Job(BaseModel):
name: str
job = Job.model_validate(row)