Skip to main content

2 posts tagged with "design-patterns"

design-patterns tag description

View All Tags

Why Use a Pydantic Model for a Single Attribute (The Wrapper Pattern)

· 6 min read
Serhii Hrekov
software engineer, creator, artist, programmer, projects founder

It might seem excessive to define an entire Pydantic BaseModel for a single attribute when a simple type hint like user_id: str would suffice. However, using a single-attribute Pydantic model (often called a Wrapper Model or a Value Object) offers significant advantages, primarily around reusability, centralized validation, and complex parsing.

This pattern transforms a simple type hint into a powerful, reusable validation layer.

The Wrapper Pattern in Python: Definition and Strategic Use Cases

· 7 min read
Serhii Hrekov
software engineer, creator, artist, programmer, projects founder

The Wrapper Pattern (often referred to in design literature as the Decorator Pattern or Adapter Pattern when applied to classes, but used here in the broader sense of wrapping functionality or data) involves encapsulating an object or a function within another object.

In the context of Python, particularly with frameworks like FastAPI and Pydantic, the Wrapper Pattern is primarily used to:

  1. Enhance or Extend Functionality without modifying the original object (Decorator/Adapter).
  2. Validate and Centralize Logic for a simple data type, turning it into a Value Object (as seen with Pydantic).