-
-
Save pedroserrudo/80f7094bf70ac371695a6024eecbbaf1 to your computer and use it in GitHub Desktop.
Generic solution for `@dataclass` validation in Python with custom setters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment