
Talk Python To Me #466: Pydantic Performance Tips
23 snips
Jun 14, 2024 Sydney Runkle shares Pydantic performance tips to optimize code efficiency, covering techniques like using tag unions for discrimination in validation, efficient creation of type adapters, and strategies for importing code specifications. The discussion also explores discriminators for nested models, 'skip validation' annotations, and tools like CODSPEED for benchmark tests. Learn about Pydantic's impact on projects like FastAPI and the potential integration with large language models for enhanced productivity.
AI Snips
Chapters
Transcript
Episode notes
Skip Python JSON Materialization
- Use Pydantic's model_validate_json to parse JSON directly instead of json.loads then model_validate.
- This avoids materializing Python objects and sends the string straight to the Rust core for faster validation.
Initialize TypeAdapters Once
- Create TypeAdapter instances once and reuse them instead of constructing them inside loops or repeated calls.
- Reusing type adapters avoids rebuilding core schemas repeatedly and yields large speedups.
Prefer Specific Type Hints
- Be specific in type hints (List[int], Dict[str,int]) rather than generic types like Sequence or Mapping.
- Precise types let Pydantic use optimized validation paths and improve speed.

