I want to add validations for my class attributes. On exploring, I came across multiple libraries google appengine, dj have their own property classes to validate attributes. Since its a common problem, Is there any python library which just provides basic validators ?
Asked
Active
Viewed 3,419 times
2 Answers
1
You can use pyfields
, it makes it very easy to add validation to class fields, independently of how you create the constructor (although pyfields
also provides ways to create the constructor easily).
For example:
from pyfields import field
class Position:
x = field(validators=lambda x: x > 0)
y = field(validators={'y should be between 0 and 100': lambda y: y > 0 and y < 100})
p = Position()
p.x = 1
p.y = 101 # error see below
yields
valid8.entry_points.ValidationError[ValueError]:
Error validating [Position.y=101]. InvalidValue: y should be between 0 and 100.
Function [<lambda>] returned [False] for value 101.
It is fully compliant with mini-lambda
and valid8
's validation lib, so that it is easy to add many validators to your fields, while keeping code readability :
from pyfields import init_fields
from mini_lambda import x
from valid8.validation_lib import is_in
ALLOWED_COLORS = {'white', 'blue', 'red'}
class Wall:
height: int = field(validators={'should be a positive number': x > 0,
'should be a multiple of 100': x % 100 == 0},
doc="Height of the wall in mm.")
color: str = field(validators=is_in(ALLOWED_COLORS),
default='white',
doc="Color of the wall.")
@init_fields
def __init__(self, msg):
print(msg)
w = Wall("hello world!", height=100)
print(vars(w))
See documentation for details (I'm the author by the way ;) )

smarie
- 4,568
- 24
- 39
0
validation in python classes can make from method class.you should see the object-oriented programming in python articles for more detail.
from datetime import datetime
class Person(object):
def __init__(self, years):
self.age = years
@property
def age(self):
return datetime.now().year - self.birthyear
@age.setter
def age(self, years):
if years < 0:
raise ValueError("Age cannot be negative")
self.birthyear = datetime.now().year - years
# p = Person(-1)
# ValueError: Age cannot be negative
# p = Person(10)
# p.age = -1
# ValueError: Age cannot be negative
p = Person(19)
print(p.age) # 19
p.age = p.age + 1
print(p.age) # 20
p.birthyear = 1992
print(p.age) # 23
or try this link: https://smarie.github.io/python-valid8/

Babak Abadkheir
- 2,222
- 1
- 19
- 46