Declarative Field Validation in Python Classes
Most data classes in production code start the same way: a handful of fields, a constructor, and then a scattering of if checks that raise somewhere in the middle. Validation written that way is late, partial, and duplicated. It runs after the object exists, reports one problem at a time, and drifts as fields are added because nothing forces the checks to stay in sync with the declarations.
A declarative approach inverts the relationship. Fields and their rules are stated once, next to each other, and the class machinery turns that declaration into storage, validation, and error reporting automatically. The same declaration can also drive serialization, documentation, and defaults, because there is a single source of truth rather than four parallel lists.
This lesson builds such a system, then compares the three ways Python lets you attach the machinery: a metaclass, __init_subclass__, and descriptors combined with a decorator.
What You'll Learn
- 1Declare fields with annotations and read them back at class creation
- 2Attach validation rules to fields without repeating them in the constructor
- 3Accumulate all field errors and raise one informative exception
- 4Pick the lightest machinery that supports the declaration you need
Reading a class declaration like data
A class body is executed into a plain namespace before the class object exists, so every assignment you write there is visible afterwards through vars(cls). Annotations written next to those assignments are collected separately in __annotations__ and are never enforced by Python, which is exactly what makes them a convenient place to document intent. Markers, being real objects, are the part the machinery can act on.
class Field:
def __init__(self, *, min=None, max=None, choices=None, default=None):
self.min = min
self.max = max
self.choices = choices
self.default = default
class Address:
city = Field(min=1, max=80)
postcode = Field(min=4, max=12)
country = Field(choices={"PT", "ES", "FR"})
def declared_fields(cls):
found = {}
for name, attribute in vars(cls).items():
if isinstance(attribute, Field):
found[name] = attribute
return found
print(list(declared_fields(Address))) # ['city', 'postcode', 'country']
The helper scans the class namespace and keeps only the names whose attribute is actually a Field marker, ignoring anything else. That distinction matters: a class may carry type hints for documentation without wanting them validated, so the presence of a marker, not the presence of an annotation, decides what enters the schema.
Three ways to act on the declaration
Python offers three hook points for reacting to a class body, and they differ in scope and timing rather than in raw power.
| Hook | Runs when | Scope | Best for |
|---|---|---|---|
Metaclass __new__ | The class statement executes | Every subclass unless overridden | Frameworks that own the class entirely |
__init_subclass__ | A subclass is created | The defining class and its descendants | Opting in with a base class, no extra type |
| Class decorator | Immediately after the class body | Only the decorated class | One-off transformations, easiest to test |
For an application-level schema, __init_subclass__ is usually the right size. It keeps the metaclass free for frameworks, needs no extra import, and reads plainly: inherit from a base, and the base processes your declarations. The decorator variant wins when you want the schema to be optional and explicitly requested at the definition site.
class Schema:
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)
rules = {}
for name, marker in list(vars(cls).items()):
if isinstance(marker, Field):
rules[name] = marker
setattr(cls, name, marker.default)
cls.__fields__ = rules
def __init__(self, **values):
errors = {}
cleaned = {}
for name, rule in self.__fields__.items():
if name not in values:
if rule.default is None:
errors[name] = "is required"
continue
value = rule.default
else:
value = values[name]
problem = self._check(name, value, rule)
if problem:
errors[name] = problem
else:
cleaned[name] = value
if errors:
raise ValidationError(errors)
self.__dict__.update(cleaned)
@staticmethod
def _check(name, value, rule):
if rule.choices is not None and value not in rule.choices:
return f"must be one of {sorted(rule.choices)}"
if isinstance(value, str):
if rule.min is not None and len(value) < rule.min:
return f"must be at least {rule.min} characters"
if rule.max is not None and len(value) > rule.max:
return f"must be at most {rule.max} characters"
elif isinstance(value, (int, float)):
if rule.min is not None and value < rule.min:
return f"must be >= {rule.min}"
if rule.max is not None and value > rule.max:
return f"must be <= {rule.max}"
return None
class ValidationError(Exception):
def __init__(self, errors):
self.errors = errors
super().__init__("; ".join(f"{k} {v}" for k, v in errors.items()))
class Signup(Schema):
email = Field(min=5, max=120)
plan = Field(choices={"free", "pro", "team"}, default="free")
try:
Signup(email="nope", plan="enterprise")
except ValidationError as exc:
print(exc.errors)
Note what the base class does not do: it does not rewrite __init__, does not wrap methods, and does not touch subclasses it never sees. It reads the declarations that already exist and installs the rules. That restraint is what makes the pattern readable six months later.
Collecting every error, not the first one
A schema that raises on the first bad field forces a frustrating loop of fix and resubmit. Accumulating errors changes the interaction: the caller receives a complete report, the form highlights every problem, and the exception itself becomes a data structure rather than a sentence.
The cost is that validation must be side-effect free. If a check writes to a database or mutates the object before all fields have been examined, a later failure leaves partial state behind. Keep each check a pure function of the value and its rule, build the cleaned dictionary separately, and publish it only when the error map is empty.
That pattern also composes with nested schemas. When a field is itself a Schema subclass, the check becomes a recursive construction whose failure returns its own nested error dictionary. The top-level exception then carries a tree of errors, which is exactly what a JSON API wants to return to a client.
Nested shapes: lists and sub-schemas
Real payloads are not flat. An order has a list of line items, and each line item has its own fields and its own rules. The clean way to support that is to let the per-field check recognize two new marker kinds: a field whose type is another schema subclass, and a field that wraps such a schema in a list. Each recurses, and each returns either a cleaned value or an error fragment that the parent collects.
Indexing matters in the report. An error on the third line item should read something like line 2 in the payload, or items.2.amount in the key, because a flat message such as amount is invalid gives whoever fixes the data no idea which of several amounts to change. Building the key by joining the path as the recursion descends costs almost nothing and turns the error dictionary into a structure a form or an API client can render directly.
The alternative, flattening nested validation into one long method, becomes unreadable by the third level and forces every new nested type into the same function. Recursion keeps each schema responsible for its own shape, which is the same reason view functions in a web framework are split per resource rather than gathered into one dispatcher.
Testing the schema without testing the framework
A schema system earns trust through tests that pin its observable behavior rather than its internals. Three groups cover almost everything. Construction tests check that valid data produces an object whose attributes match what was passed, and that defaults appear when a field is omitted. Rejection tests check that each rule rejects its own violation, and that the error dictionary contains both the field name and a message a human can act on. Aggregation tests check that a payload with several problems reports all of them at once rather than stopping at the first.
Parametrization is the natural tool for the rejection group: one test body, a table of value-and-message pairs, and a separate reported case for each. Add one test that deliberately omits a required field and one that passes an unknown field, because the handling of unknown keys is a decision the system must make explicitly, even if the answer is to ignore them.
Finally, keep a test that inspects the declared rules themselves, such as the set of names in the schema mapping. It looks like a tautology until someone renames a field, at which point it becomes the fastest possible notification that the rename is incomplete.
Where this approach stops paying
Declarative validation wins for flat, form-shaped data with rules that map cleanly onto a marker. It gets awkward when a rule needs context that the class does not have, such as checking a username against a table or comparing two fields to each other. Cross-field rules belong in an explicit clean or validate step that runs after per-field checks, where they can read the cleaned values together.
It is also the wrong tool when you only need type hints for documentation, or when the data already arrives validated from a trusted source and the checks are pure ceremony. Frameworks such as Pydantic and attrs exist because the general problem is large; a forty-line base class earns its place when the requirements genuinely stay this small.
Common Mistakes
Treating every annotation as a validated field
Fix: Gate the schema on an explicit marker object so documentation-only hints stay inert
Raising on the first invalid field
Fix: Accumulate errors into a dictionary and raise once, carrying the whole report
Running side-effecting checks before all fields are validated
Fix: Keep per-field checks pure, build a cleaned mapping, and publish it only when no errors remain
Building a metaclass for a one-class transformation
Fix: Use a class decorator or __init_subclass__ and reserve metaclasses for frameworks that need to own class creation
Best Practices
- Store field rules on the class as a single __fields__ mapping that serializers can reuse
- Expose errors as a dictionary so HTTP layers and forms can consume them directly
- Keep the marker classes small and data-only; behavior belongs on the schema base
- Document cross-field rules in one explicit method rather than spreading them across markers
- Add a test that asserts the collected error set, not just that an exception was raised
Interview Questions
Q1: What does __init_subclass__ give you that a metaclass does not?
It lets an ordinary base class participate in subclass creation without changing the type hierarchy, so classes remain instances of type and can still be combined with metaclasses defined elsewhere.
Q2: Why store rules in __fields__ instead of reading annotations each time?
The class body may contain markers, defaults, and plain hints together. Building one normalized mapping at creation time avoids repeating that scan on every instantiation and gives other tools a stable interface.
Q3: How would you support validating one field against another?
Run per-field checks first into a cleaned mapping, then call a cross-field method that receives the cleaned values and appends errors keyed by field name before anything is published.
Key Takeaways
- Annotations are free-form data; a marker object decides what becomes a validated field
- A single declaration can drive validation, defaults, and serialization
- __init_subclass__ is usually the lightest hook for application-level schemas
- Collect every error and raise once so callers get a complete report
- Keep checks pure and defer side effects until validation has fully succeeded