Created
May 15, 2021 05:25
-
-
Save tanduong/4f192b831b4e32b28982e97b746dad0b to your computer and use it in GitHub Desktop.
Python Validation
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 abc import ABC, abstractmethod | |
class Validator(ABC): | |
def __set_name__(self, owner, name): | |
self.private_name = f'_{name}' | |
def __get__(self, obj, objtype=None): | |
return getattr(obj, self.private_name) | |
def __set__(self, obj, value): | |
self.validate(value) | |
setattr(obj, self.private_name, value) | |
@abstractmethod | |
def validate(self, value): | |
pass | |
class OneOf(Validator): | |
def __init__(self, *options): | |
self.options = set(options) | |
def validate(self, value): | |
if value not in self.options: | |
raise ValueError(f'{value!r} is not a valid option. Should be one of {self.options!r}') | |
class Sample: | |
group = OneOf('A', 'B') | |
def __init__(self, group): | |
self.group = group | |
Sample('A') # OK | |
Sample('C') # 'C' is not a valid option. Should be one of {'A', 'B'} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment