Junior — Middle
What methods can be used to implement a class for input data validation?
sobes.tech AI
Answer from AI
To implement a class for input data validation in Python, several approaches can be used:
-
Class methods — write methods that check specific conditions (e.g., type, range, format).
-
Using exceptions — raise an exception when an error is detected to handle incorrect data.
-
Regular expressions — for checking strings against patterns.
-
Using third-party libraries — for example,
pydanticorcerberusfor more complex validation.
Example of a simple validation class:
import re
class Validator:
def is_email(self, value):
pattern = r'^[\w\.-]+@[\w\.-]+\.\w+$'
return bool(re.match(pattern, value))
def is_positive_int(self, value):
return isinstance(value, int) and value > 0
def validate_user(self, data):
if not self.is_email(data.get('email', '')):
raise ValueError('Invalid email')
if not self.is_positive_int(data.get('age', 0)):
raise ValueError('Age must be a positive integer')
# Usage
validator = Validator()
user_data = {'email': 'test@example.com', 'age': 25}
validator.validate_user(user_data) # Will raise an exception if data is incorrect