Dataclass with validation
Validate and normalize fields in __post_init__ so invalid objects can never be created.
- Python
- GreenSnippets
- MIT
- Executed with Python 3.11
from dataclasses import dataclass
@dataclass(frozen=True)
class User:
name: str
email: str
age: int
def __post_init__(self):
if not self.name.strip():
raise ValueError("name is required")
if "@" not in self.email:
raise ValueError("email is invalid")
if not 0 <= self.age <= 150:
raise ValueError("age out of range")
object.__setattr__(self, "email", self.email.strip().lower())Example / expected output
User("Ada", "ADA@Example.com", 36).email # 'ada@example.com'How it works
Dataclasses remove boilerplate but do not validate. __post_init__ runs after the generated __init__, so it is the place to check ranges and normalize values. frozen=True makes instances immutable, which keeps the validated state valid.
Related snippets
- PHP Tested
Validate emails and URLs in PHP
Use filter_var to validate email addresses and http(s) URLs, with an allow-list for schemes.
- TypeScript Tested
Parse JSON into a typed value with a guard
Safely turn unknown JSON into a typed result by validating its shape instead of casting.
- TypeScript Tested
Typed fetch helper that checks the response
A fetch wrapper that throws on HTTP errors and validates the JSON body with a type guard.
- PHP Tested
Decode JSON safely in PHP
Parse JSON with exceptions on error and a depth limit, instead of silently getting null.

