How to Validate Data Types in Python with a Class

A beginner-friendly Python class that checks if a value is a string, integer, float, list, or empty, using simple methods and isinstance checks.

Easy Python 3.9+ Aug 9, 2026 OOP & classes 13 views 0 copies

Python code

37 lines
Python 3.9+
class DataValidator:
    """A simple data validation helper for beginners."""
    
    def __init__(self, data):
        self.data = data
    
    def is_string(self):
        return isinstance(self.data, str)
    
    def is_integer(self):
        return isinstance(self.data, int) and not isinstance(self.data, bool)
    
    def is_float(self):
        return isinstance(self.data, float)
    
    def is_list(self):
        return isinstance(self.data, list)
    
    def is_empty(self):
        if self.is_string() or self.is_list():
            return len(self.data) == 0
        return self.data is None


if __name__ == "__main__":
    validator = DataValidator("hello")
    print(f"String: {validator.is_string()}")
    print(f"Integer: {validator.is_integer()}")
    print(f"Empty: {validator.is_empty()}")
    
    num_validator = DataValidator(42)
    print(f"Integer: {num_validator.is_integer()}")
    print(f"Float: {num_validator.is_float()}")
    
    list_validator = DataValidator([])
    print(f"List: {list_validator.is_list()}")
    print(f"Empty list: {list_validator.is_empty()}")

Output

stdout
String: True
Integer: False
Empty: False
Integer: True
Float: False
List: True
Empty list: True

How it works

The class stores the data passed to __init__ and exposes methods that use isinstance to verify the type. is_integer explicitly excludes booleans because bool is a subclass of int in Python. is_empty handles strings and lists by checking length, and any other type by checking for None. This pattern keeps validation logic reusable and easy to test.

Common mistakes

  • Forgetting that booleans are integers, so `isinstance(True, int)` returns True.
  • Using `== 0` instead of `len()` for empty strings or lists, which fails on `None`.
  • Not handling `None` separately in `is_empty`, causing an error when calling `len` on `None`.

Variations

  1. Use `@property` to make validation checks like `validator.is_string` without parentheses.
  2. Add a `validate()` method that returns a dictionary of all checks at once.

Real-world use cases

  • Validating user input in a CLI tool before processing to avoid type-related crashes.
  • Preprocessing API response JSON to ensure fields are the expected types before database insertion.
  • Building small config parsers that verify each setting's type when loading a file.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from OOP & classes

Related tutorials and quizzes for this topic.