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 FastAPI, WebSocket, WebSocketDisconnect app = FastAPI()
Building a WebSocket chat with FastAPI
websockets
broadcast
connection-management
Intermediate
9 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
python
import random from typing import Iterator, List
How reservoir sampling picks k items
reservoir-sampling
streaming
randomness
Intermediate
5 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
python
import re from functools import total_ordering from typing import Optional
Parsing and comparing semantic versions
regex
operator-overloading
sorting
Intermediate
7 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.