Skip to content

Pydantic Plugin: Test, document and configure Union type coercion behavior #26

@genro

Description

@genro

Context

Union types are likely already validated by Pydantic v2's create_model() that the plugin uses. However, the exact behavior needs to be understood, tested, and documented, especially regarding Pydantic's coercion which depends on type order in the Union.

Implementation Plan

1. Add Dedicated Tests

Test Union type behavior with various cases:

  • Union[int, str, dict] - basic multi-type union
  • Union[int, str] with input "42" - test coercion to int
  • Union[int, str] with input 3.14 - test float coercion
  • Union[str, int] with same inputs - verify order matters
  • Edge cases with Optional, None, etc.

These tests will clarify what actually happens in the plugin.

2. Document Coercion Behavior

Add clear documentation explaining:

  • Pydantic v2 uses stack order: Union[int, str] tries int first
  • String "42" will be coerced to int if int comes first
  • How to control this behavior (see next point)

3. Configuration Option for Coercion Control

Add optional configuration to control Union coercion:

# Allow coercion (default, matches Pydantic behavior)
sw = Switcher().plug("pydantic", coerce_union=True)

# Disable coercion (stricter type matching)
sw = Switcher().plug("pydantic", coerce_union=False)

When coerce_union=False, document how users can use Annotated[str, Field(strict=True)] for fine-grained control (requires #14 implementation).

Work Breakdown

This is primarily a test + documentation task:

  • ✅ Core functionality likely already works
  • 🔧 Need comprehensive tests to verify behavior
  • 📝 Need documentation explaining coercion rules
  • ⚙️ Optional: add coerce_union configuration flag

Related Issues

Priority

Medium - Works now, but needs proper testing and documentation before users rely on it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions