facebook / facebook/pyrefly

Implement static checking for model_validate in pydantic

Open
#1,123 3 comments 0 reactions 1 assignee Claimed by @asukaminato0721 View on GitHub
pydantic
Dominant language
Rust
Stars
7k
Forks
519
PR merge metrics
No merged PRs in 30d

Description

### Describe the Bug

We can consider implementing static typechecking for model_validate, which is a function in pydantic that validates models at runtime.

We should think about the level of strictness we want to implement here, considering there will be cases where runtime coercion is used.

```
"""
Nested structures with business rules.
- Inventory items must have quantity >= 1.
- Intentional error: one item has negative quantity.
Expected: ValidationError pointing to items[1].quantity.
"""
from pydantic import BaseModel, ValidationError, Field

class Item(BaseModel):
sku: str
quantity: int = Field(ge=1)

class Inventory(BaseModel):
items: list[Item]

bad = {
"items": [
{"sku": "A-100", "quantity": 5},
{"sku": "B-200", "quantity": -3}, # <-- invalid!!!! we can raise a type error here
]
}

try:
Inventory.model_validate(bad)
except ValidationError as e:
print("ValidationError for nested list rules:")
print(e)
```

### Sandbox Link

_No response_

### (Only applicable for extension issues) IDE Information

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.