1 of 21

Why Use Pydantic?

  • Powered by type hints
  • Speed
  • JSON Schema and documentation
  • Custom validation / serialization logic
  • Robust ecosystem (FastAPI, Django, SQLModel, Beanie, etc…)
  • Extensive community

2 of 21

Basic Performance Tips

3 of 21

Opinionated JSON Loading Syntax

  • Use model_validate_json(...)
    • Not model_validate(json.loads(...))
  • Exception: some model validators
    • before, wrap

4 of 21

Bad:

Good:

TypeAdapter Tips

5 of 21

Specificity for Sequence and Mapping Type Hints

  • Use list, tuple, etc instead of Sequence
    • Avoid isinstance(x, Sequence)checks
  • Use dict instead of Mapping
  • Maximal specificity → better performance
    • (in these cases)

6 of 21

Using Tagged Unions

7 of 21

Agenda

  • What are tagged unions?
  • Basic example
  • Why use tagged unions?
    • Validation performance
    • Improved error handling
    • JSON schema compatibility
  • Advanced examples
    • Callable discriminators
    • Nested models and tagged unions

8 of 21

What are Tagged Unions?

  • Special type of Union
  • Also called discriminated unions
  • Specify member of Union to validate against
    • Based on a “tag”, also called “discriminator”
  • Discriminators can be of str or Callable type

9 of 21

A Basic Example

10 of 21

A Basic Example, cont.

11 of 21

Efficient Validation

  • Avoid validating against all union members
  • Beneficial with nested models, in particular
  • Crucial when models have tons of fields

12 of 21

Improved Error Handling

13 of 21

Improved Error Handling

14 of 21

Improved Error Handling

15 of 21

JSON Schema Compatibility

16 of 21

Callable Discriminators

17 of 21

Nested Models and Tagged Unions

18 of 21

Nested Models and Tagged Unions

19 of 21

Performance Improvements in the Pipeline

  • SIMD in jiter
  • Parsing JSON as validation happens
  • FastModel
  • Schema building speedup

20 of 21

Pydantic Logfire is in Open Beta!

  • Easy to use observability platform
    • “Find the needle in the stacktrace” philosophy
  • Python-centric insights
    • Event loop telemetry
    • Profiling code and database queries
  • Structured data and SQL access
  • Opinionated OpenTelemetry wrapper
  • Seamless Pydantic integration

21 of 21