python
45 lines · 8 steps
Type-checking dataclasses at runtime
A validator that reads dataclass type hints and checks incoming dict data against them, including unions and generic containers.
Explained by
highlit
1from dataclasses import dataclass, fields, MISSING
2from typing import get_type_hints, get_origin, get_args, Union
3
4
5class ValidationError(Exception):
6 def __init__(self, errors: dict[str, str]):
7 self.errors = errors
8 super().__init__(f"{len(errors)} validation error(s)")
9
10
11def _check_type(value, expected) -> bool:
12 origin = get_origin(expected)
13 if origin is Union:
14 return any(_check_type(value, arg) for arg in get_args(expected))
15 if origin in (list, tuple, set):
16 if not isinstance(value, origin):
17 return False
18 (inner,) = get_args(expected) or (object,)
19 return all(_check_type(item, inner) for item in value)
20 if expected is type(None):
21 return value is None
22 return isinstance(value, expected)
23
24
25def validate(schema, data: dict):
26 hints = get_type_hints(schema)
27 errors: dict[str, str] = {}
28 kwargs = {}
29
30 for field in fields(schema):
31 name, expected = field.name, hints[field.name]
32 if name not in data:
33 if field.default is not MISSING or field.default_factory is not MISSING:
34 continue
35 errors[name] = "missing required field"
36 continue
37 value = data[name]
38 if not _check_type(value, expected):
39 errors[name] = f"expected {expected}, got {type(value).__name__}"
40 else:
41 kwargs[name] = value
42
43 if errors:
44 raise ValidationError(errors)
45 return schema(**kwargs)
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Python's typing introspection lets you walk generic types at runtime by peeling off origins and args.
- 2Recursion mirrors the structure of nested types, so a union or a list of unions validates with the same function.
- 3Collecting all errors before raising gives callers a complete picture rather than failing on the first problem.
Related explainers
python
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status from pydantic import BaseModel, EmailStr from sqlalchemy.orm import Session
Building a signup endpoint in FastAPI
dependency-injection
request-validation
background-tasks
Intermediate
8 steps
python
from django import forms from django.utils import timezone from .models import Reservation
Multi-field validation in a Django ModelForm
form validation
cross-field validation
modelform
Intermediate
7 steps
java
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map;
Building a trie for autocomplete in Java
trie
prefix-tree
recursion
Intermediate
8 steps
ruby
class KeyTransformer def self.camelize(data) new.camelize(data) end
Recursively camelizing nested Ruby data
recursion
data-transformation
pattern-matching
Intermediate
7 steps
python
from django import template from django.urls import reverse, NoReverseMatch from django.utils.html import format_html
Active nav-link template tags in Django
template tags
url routing
active state
Intermediate
7 steps
python
from functools import wraps import asyncio from fastapi import APIRouter, FastAPI, Request
Per-route request timeouts in FastAPI
decorators
async
timeouts
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/type-checking-dataclasses-at-runtime-explained-python-cb9a/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.