Skip to content

Instantly share code, notes, and snippets.

@mikybars
Last active May 24, 2023 19:11
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mikybars/07397a021314a5020d0f7e2708eb175e to your computer and use it in GitHub Desktop.
Save mikybars/07397a021314a5020d0f7e2708eb175e to your computer and use it in GitHub Desktop.
Generic solution for `@dataclass` validation in Python with custom setters
from dataclasses import dataclass
class Validations:
def __setattr__(self, prop, val):
if (validator := getattr(self, f"validate_{prop}", None)):
object.__setattr__(self, prop, validator(val) or val)
else:
super().__setattr__(prop, val)
@dataclass
class Person(Validations):
name: str
age: int
gender: str = "FEMALE"
def validate_gender(self, value) -> str:
if value.lower() not in ["male", "female"]:
raise ValueError("gender must be MALE or FEMALE")
return value.upper()
def validate_age(self, value):
if value < 1 or value > 100:
raise ValueError("age must be between 1 and 100")
@pedroserrudo
Copy link

this is great! have been using it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment