Created
February 24, 2023 10:08
-
-
Save pedroserrudo/05fccbf7a4ecf6ef672c6473aeefeb47 to your computer and use it in GitHub Desktop.
dataclasses field validation similar to django
This file contains 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