Validate Dataclass Fields in __post_init__
Enforce types and ranges on dataclass fields at construction time, normalize values, and raise one error listing every invalid field.
Code
from dataclasses import dataclass
class ValidationError(ValueError):
def __init__(self, errors: dict[str, str]) -> None:
self.errors = errors
message = "; ".join(f"{field}: {text}" for field, text in errors.items())
super().__init__(message)
@dataclass
class Signup:
email: str
age: int
username: str
def __post_init__(self) -> None:
errors: dict[str, str] = {}
email = self.email.strip().lower()
if email.count("@") != 1 or email.startswith("@") or email.endswith("@"):
errors["email"] = "must contain one @ with local and domain parts"
else:
self.email = email
if isinstance(self.age, bool) or not isinstance(self.age, int):
errors["age"] = "must be an integer"
elif not 13 <= self.age <= 120:
errors["age"] = "must be between 13 and 120"
username = self.username.strip()
if not 3 <= len(username) <= 20:
errors["username"] = "must be 3-20 characters"
elif not username.replace("_", "").isalnum():
errors["username"] = "may contain only letters, digits, and underscores"
else:
self.username = username
if errors:
raise ValidationError(errors)
def main() -> None:
print(Signup(email=" ADA@Example.com ", age=36, username=" ada_1 "))
try:
Signup(email="nope", age=True, username="x")
except ValidationError as error:
print(error)
print(error.errors)
if __name__ == "__main__":
main()
Output
Captured from a sandboxed run of this snippet in the build pipeline.
Signup(email='ada@example.com', age=36, username='ada_1')
email: must contain one @ with local and domain parts; age: must be an integer; username: must be 3-20 characters
{'email': 'must contain one @ with local and domain parts', 'age': 'must be an integer', 'username': 'must be 3-20 characters'}How it works
Validate Dataclass Fields in post_init is built around the class class and the functions __init__, __post_init__ and main.
Invalid states are rejected up front: it throws ValidationError instead of continuing with bad data.
Points of care
- The guard
errorsshort-circuits the flow with an earlyraisewhen its condition holds.
Putting it to use
The primary signature is def main() -> None
Core lines
def __init__(self, errors: dict[str, str]) -> None:
self.errors = errors
message = "; ".join(f"{field}: {text}" for field, text in errors.items())
super().__init__(message)
def main() -> None:
print(Signup(email=" ADA@Example.com ", age=36, username=" ada_1 "))
try:
Signup(email="nope", age=True, username="x")
except ValidationError as error:
print(error)
print(error.errors)
elif not username.replace("_", "").isalnum():
errors["username"] = "may contain only letters, digits, and underscores"
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- How are precondition violations signaled?
- `ValidationError` is raised at the guard (`errors`), so invalid state never reaches the main logic.
- How do you run Validate Dataclass Fields in __post_init__?
- The file is self-contained: run it directly, no dependencies to install beforehand.
Report a problem with this exampleOpens a pre-filled issue on GitHub.