Skip to content

Instantly share code, notes, and snippets.

@tanduong
Created May 15, 2021 05:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanduong/4f192b831b4e32b28982e97b746dad0b to your computer and use it in GitHub Desktop.
Save tanduong/4f192b831b4e32b28982e97b746dad0b to your computer and use it in GitHub Desktop.
Python Validation
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