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.
Python code
37 linesclass 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
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
- Use `@property` to make validation checks like `validator.is_string` without parentheses.
- 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
More from OOP & classes
- Add property getter setter validation in Python easy
- Binary Tree Inorder Traversal in Python easy
- Borg pattern shared state in Python medium
- Bridge Pattern in Python: Separate Abstraction from Implementation medium
- Composable Predicates with the &, |, ~ Operators in Python medium
- Composition over Inheritance: How to Build a Wallet Account in Python easy
Keep learning
Related tutorials and quizzes for this topic.