Sobes.tech
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:

  1. Class methods — write methods that check specific conditions (e.g., type, range, format).

  2. Using exceptions — raise an exception when an error is detected to handle incorrect data.

  3. Regular expressions — for checking strings against patterns.

  4. Using third-party libraries — for example, pydantic or cerberus for 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
What methods can be used to implement a class for… - sobes.tech