Skip to main content

Skill Guide

Pydantic v2 data modeling with strict mode, discriminated unions, and custom validators

Pydantic v2 data modeling is the practice of defining strict, self-validating Python data schemas using Pydantic's v2 library, with strict mode enforcing exact type adherence, discriminated unions enabling type-safe heterogeneous data structures, and custom validators embedding complex business logic directly into the model layer.

This skill is highly valued because it shifts runtime data errors to development time, dramatically increasing API and data pipeline reliability while reducing defensive boilerplate code. It directly impacts business outcomes by preventing data corruption bugs, accelerating feature development with robust contracts, and enabling cleaner system integrations.
1 Careers
1 Categories
8.5 Avg Demand
20% Avg AI Risk

How to Learn Pydantic v2 data modeling with strict mode, discriminated unions, and custom validators

Focus on: 1) Core Pydantic v2 BaseModel and field definitions, understanding `model_config` settings. 2) Implementing basic `@field_validator` and `@model_validator` decorators. 3) Using `Union` types with a `discriminator` field for simple polymorphic responses.
Move to practice by: 1) Enabling `model_config = ConfigDict(strict=True)` and debugging resulting `ValidationError`s for type mismatches. 2) Building a `RootModel` for complex, validated list/dict structures. 3) Avoiding common pitfalls like mutable default arguments in fields or misusing `Optional` in strict mode.
Master by: 1) Designing custom `__get_pydantic_core_schema__` for non-standard types (e.g., a custom email class with domain-specific validation). 2) Architecting large-scale discriminated union hierarchies for event sourcing or plugin systems. 3) Optimizing validator chains and using `model_serializer` for performance-critical serialization.

Practice Projects

Beginner
Project

Strict User & Address API Model

Scenario

Build data models for a user registration API where all fields must match exact types (no implicit coercion) and the address can be one of several formats (US, UK, International) selected by a 'country_code' discriminator.

How to Execute
1. Define `UserBase` with `model_config = ConfigDict(strict=True)`. 2. Create `AddressUS`, `AddressUK` models. 3. Define `Address = Annotated[Union[AddressUS, AddressUK], Field(discriminator='country_code')]`. 4. Write a test suite that sends valid/invalid data and checks `ValidationError` outputs.
Intermediate
Project

Event Sourcing with Discriminated Commands

Scenario

Model a command bus where each command (e.g., 'CreateOrder', 'UpdateInventory') is a Pydantic model. The system must deserialize a JSON payload and route it to the correct handler based on a top-level 'event_type' field.

How to Execute
1. Create a base `Command` model with a `Literal['create_order', 'update_inventory']` `event_type` field. 2. Define concrete command models inheriting from it. 3. Use `RootModel[Annotated[Union[CreateOrder, UpdateInventory], Field(discriminator='event_type')]]` as the entry point. 4. Implement a custom validator that checks business rules (e.g., order total > 0) within the command model.
Advanced
Project

Plugin-Driven Configuration Validator

Scenario

Design a configuration system for a plugin architecture where each plugin defines its own schema. The main config file is validated by dynamically assembling a discriminated union of all installed plugin schemas.

How to Execute
1. Define a plugin interface using an abstract Pydantic model with a required `plugin_type: Literal` field. 2. Use a registry pattern to collect plugin models at startup. 3. Dynamically construct the master `Config` model using `Union[tuple(registered_plugins)]` with the `plugin_type` discriminator. 4. Implement a `model_validator(mode='after')` that performs cross-plugin dependency validation (e.g., Plugin A requires Plugin B's settings).

Tools & Frameworks

Core Libraries & Tools

Pydantic V2Pydantic Coremypy with pydantic pluginpytest

Pydantic V2 is the primary toolkit. The `pydantic` mypy plugin provides static analysis for model code. Use `pytest` to systematically test validation logic and error messages.

Supporting Ecosystem

FastAPISQLModelPydantic Factories (for testing)

FastAPI leverages Pydantic for request/response validation. SQLModel integrates it with ORM. `pydantic-factories` or `hypothesis` generate test data conforming to complex models.

Development & Debugging

VS Code with PylancePydantic's `.model_json_schema()` methodLogging of `ValidationError`

Use IDE type hints for immediate feedback. Generate JSON Schema for API documentation. Log validation errors with full context during development to trace issues.

Interview Questions

Answer Strategy

The interviewer is testing knowledge of discriminated unions and API design. Explain the use of `Annotated[Union[Notification, Command], Field(discriminator='type')]` with a `Literal` type field on each model. Highlight benefits: O(1) deserialization performance, clear error messages, and automatic API docs. Sample Answer: 'I'd use a discriminated union keyed on the `type` field, which must be a `Literal` in each model. This ensures deserialization is fast and type-safe, avoids slow linear union checking, and provides precise validation errors like "type 'alert' is not valid for Command" rather than generic union failures.'

Answer Strategy

This tests problem-solving and mentoring. The core competency is understanding strict mode's purpose and guiding through alternatives. The answer should reinforce principles. Sample Answer: 'I'd explain that strict mode is correct for APIs to prevent subtle type bugs. The data source is sending a string, which is an integration issue. I'd recommend two fixes: 1) Fix the source to send proper JSON integers, or 2) If the source is immutable, create a separate `UserInput` model without strict mode to coerce types, then validate that into our internal `User` model which remains strict. We don't disable strict mode for the core domain model.'

Careers That Require Pydantic v2 data modeling with strict mode, discriminated unions, and custom validators

1 career found