Performance: List and set validation
This affects server response time and payload size during API request validation.
from fastapi import FastAPI from pydantic import BaseModel from typing import Set app = FastAPI() class ItemModel(BaseModel): tags: Set[str] @app.post('/items/') async def create_item(item: ItemModel): return {'unique_tags_count': len(item.tags)}
from fastapi import FastAPI from pydantic import BaseModel from typing import List app = FastAPI() class ItemModel(BaseModel): tags: List[str] @app.post('/items/') async def create_item(item: ItemModel): return {'tags_count': len(item.tags)}
| Pattern | Validation CPU Cost | Memory Usage | Response Delay | Verdict |
|---|---|---|---|---|
| List without type or constraints | High (linear with size) | High (stores duplicates) | Higher delay with large input | [X] Bad |
| Typed Set with uniqueness enforced | Medium (skips duplicates) | Lower (unique items only) | Lower delay | [OK] Good |
List instead of Set for request data validation?{"items": [1, 2, 2, 3]}?
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Set
app = FastAPI()
class Data(BaseModel):
items: Set[int]
@app.post("/unique")
def unique_items(data: Data):
return {"unique_items": list(data.items)}from pydantic import BaseModel
from typing import List, Set
class Model(BaseModel):
names: List[str]
unique_ids: List[int]
def __init__(self, **data):
super().__init__(**data)
self.unique_ids = set(self.unique_ids)Pass the test and this pattern moves unknown