Skip to main content

Value Objects: Mastering Data Validation in Python

From Primitives to Pydantic: Practical ways to enforce Domain Invariants

Updated 7 min readMarkdown
Value Objects: Mastering Data Validation in Python

Although DDD (Domain-Driven Design) is not widely adopted in the Python community, there are several resources on how to implement this approach in the language. However, relatively few of them focus on defining Value Objects in a way that reliably enforces domain invariants.

This article walks through several implementation techniques, illustrating their strengths and weaknesses with a practical example. We will also discuss how to model single-field Value Objects ergonomically and how Pydantic handles already validated model instances.

Introduction

A Value Object is defined by its value rather than by an identity and is typically immutable. One of its useful properties is that it can enforce business rules (invariants) during construction. Therefore, whenever we receive an instance of a Value Object, we can assume that its value has already been validated.

A common example is a Price class. When working with prices, developers usually use Decimal rather than float. Although this is preferable to floating-point arithmetic, Decimal alone does not enforce domain-specific constraints. For example, we may want to reject negative values or values with excessive precision such as 0.0000001.

Repeating these checks throughout the codebase is cumbersome and error-prone. A dedicated Price Value Object can centralize these rules and guarantee that every valid instance satisfies them.

Another use case, which we will focus on for the remainder of the article, is email validation. Since an email address represents a single value, it is often more natural to treat it like a simple data type rather than a complex structure. Our goal will be to validate an email address and normalize it to lowercase.

[WARNING] According to RFC 5321, the local part of an email address may be case-sensitive, although relying on this behavior is discouraged and common providers generally treat addresses case-insensitively. For simplicity, this article assumes application-level normalization where the entire address is converted to lowercase.


#0 Primitive Data Type Approach

The most straightforward way to create a single-value Value Object is to extend the corresponding primitive type. We can then validate and normalize the value during construction.

import re


class EmailAddress(str):
    _REGEX = r"^\S+@\S+\.\S+$"

    def __new__(cls, value: object):
        normalized = super().__new__(cls, value).lower()

        if not re.fullmatch(cls._REGEX, normalized):
            raise ValueError("Invalid format")

        return super().__new__(cls, normalized)

This approach is concise and convenient: EmailAddress behaves almost exactly like a regular string.

However, that is also its main weakness. Because EmailAddress inherits the entire str API, operations that make no sense for an email address are still available:

email = EmailAddress("alice@mail.com")
...
email += "\nRegards!"  # email is now a plain str

The original EmailAddress instance is immutable and remains valid. The problem is that the result of the operation is a regular str, so the variable silently loses both its domain type and the validation guarantees associated with it.

The same problem can become more significant with other primitive-based Value Objects:

price = Price(1)  # Decimal-based Value Object
...
discount = 2
price -= discount  # price may now be a plain Decimal

This makes primitive inheritance convenient, but it also exposes operations that can bypass the semantics of the domain type.

#1 Dataclass Approach

Many resources, including Cosmic Python, recommend using dataclasses. This is understandable, as they are part of the Standard Library and provide value-based equality out of the box.

import re
from dataclasses import dataclass
from typing import ClassVar


@dataclass(frozen=True)
class EmailAddress:
    value: str

    _REGEX: ClassVar[str] = r"^\S+@\S+\.\S+$"

    def __post_init__(self):
        if not isinstance(self.value, str):
            raise ValueError("Value must be a string")

        if not re.fullmatch(self._REGEX, self.value):
            raise ValueError("Invalid format")

        object.__setattr__(self, "value", self.value.lower())

[NOTE] Since the dataclass is frozen, normalization inside __post_init__() requires object.__setattr__(). This is a standard pattern for frozen dataclasses, but it adds some boilerplate.

We no longer expose inappropriate string operations directly on EmailAddress, but the implementation has become considerably more verbose.

We also have to validate the runtime type ourselves because standard dataclasses do not enforce type annotations. Our regex-based email validation is still fairly permissive as well. Instead of implementing all of this manually, we can use a validation library designed specifically for this purpose.

#2 Pydantic BaseModel Approach

This is where Pydantic becomes useful. It provides runtime parsing and validation and already includes an EmailStr type for email addresses. Using Annotated also allows us to add normalization concisely.

from typing import Annotated

from pydantic import AfterValidator, BaseModel, ConfigDict, EmailStr


class EmailAddress(BaseModel):
    value: Annotated[EmailStr, AfterValidator(lambda x: x.lower())]

    model_config = ConfigDict(frozen=True)

The class definition is now concise. However, because BaseModel represents an object with named fields, we need to use the value field whenever we construct or access our Value Object.

This becomes more visible when using the Value Object in a FastAPI request body:

from fastapi import FastAPI
from pydantic import BaseModel


app = FastAPI()


class SignUpRequestBody(BaseModel):
    email: EmailAddress
    password: str


@app.post("/sign_up")
async def sign_up(request_body: SignUpRequestBody):
    ...

Because EmailAddress is a nested Pydantic model, the client cannot directly pass a string to the email field. Instead, the expected request body looks like this:

{
  "email": {"value": "abc@gmail.com"},
  "password": "Secret123!"
}

For a single-value domain type, this representation is unnecessarily verbose.

#3 Pydantic RootModel Approach

We can solve this problem by replacing BaseModel with the lesser-known RootModel.

from typing import Annotated

from pydantic import AfterValidator, ConfigDict, EmailStr, RootModel


class EmailAddress(RootModel):
    root: Annotated[EmailStr, AfterValidator(lambda x: x.lower())]

    model_config = ConfigDict(frozen=True)

RootModel represents a model whose entire value is stored under a single root attribute. During validation and serialization, it behaves like that root value rather than like an object containing a named field.

As a result, our FastAPI endpoint now accepts the more natural representation:

{
  "email": "abc@gmail.com",
  "password": "Secret123!"
}

Inside Python, EmailAddress is still a proper domain type, and its underlying value can be accessed through .root.

One trade-off is that the domain model now depends directly on Pydantic. If keeping the domain layer completely framework-independent is an architectural requirement, a plain Python Value Object with Pydantic integration at the application boundary may be preferable. In applications that already use Pydantic extensively, however, RootModel can be a pragmatic solution.


Reusing Already Validated Value Objects

Layered architectures often involve mapping data between API models, application logic, domain objects, and persistence models. As a result, the same Value Object may appear in several Pydantic models.

Consider this simplified sign-up endpoint:

class SignUpRequestBody(BaseModel):
    email: EmailAddress
    password: str


class User(BaseModel):
    email: EmailAddress
    password_hash: str


@app.post("/sign_up")
async def sign_up(request_body: SignUpRequestBody):
    ...
    email = request_body.email
    password_hash = PasswordHasher().generate(request_body.password)

    with UnitOfWork() as unit_of_work:
        user = User(email=email, password_hash=password_hash)
        unit_of_work.repository.create(user)
    ...

Before sign_up() is executed, Pydantic validates the request body and creates an EmailAddress instance.

When that same instance is later passed to User, Pydantic does not validate it again by default. In Pydantic v2, revalidate_instances defaults to "never", which means existing model and dataclass instances are reused without running their validation logic again.

Therefore, no additional wrapper is required in this case:

class User(BaseModel):
    email: EmailAddress
    password_hash: str

If revalidation is explicitly required, Pydantic allows changing this behavior through revalidate_instances:

class EmailAddress(RootModel):
    root: Annotated[EmailStr, AfterValidator(lambda x: x.lower())]

    model_config = ConfigDict(
        frozen=True,
        revalidate_instances="always",
    )

Pydantic also provides InstanceOf, but it serves a different purpose. It can be used when a field should accept only an already constructed instance of a particular class rather than data that Pydantic can parse into that class.

from pydantic import InstanceOf


class User(BaseModel):
    email: InstanceOf[EmailAddress]
    password_hash: str

This changes the input contract of the model, so it should be used when that behavior is intentional rather than as a general optimization.


Takeaways

Pydantic provides concise runtime validation and parsing while integrating well with Python's static type annotations. For Value Objects, it can significantly reduce the amount of custom validation code required.

The main points discussed in this article are:

  • Value Objects provide value semantics and a natural place to enforce domain invariants.

  • Primitive-type inheritance is concise, but inherited operations can cause the domain type and its guarantees to be lost.

  • For single-field Pydantic Value Objects, RootModel usually provides a more natural external representation than BaseModel.

  • Pydantic v2 does not revalidate existing model instances by default; InstanceOf should only be used when a field must explicitly require an already constructed instance.

No comments yet. Be the first to comment.