How to Implement a Data Helper Class in Python
Build a beginner-friendly DataHelper class using dataclasses and key system design patterns like Command, Strategy, and Map.
Python code
52 linesfrom __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
@dataclass
class DataHelper:
"""A beginner-friendly data utility with common system design patterns."""
data: List[Dict[str, Any]] = field(default_factory=list)
def add_record(self, record: Dict[str, Any]) -> None:
"""Add a single record using the Command pattern."""
self.data.append(record)
def filter_by(self, key: str, value: Any) -> List[Dict[str, Any]]:
"""Filter records using a simple Strategy pattern."""
return [r for r in self.data if r.get(key) == value]
def transform(self, key: str, func) -> List[Any]:
"""Apply a transformation to a key across all records (Map pattern)."""
return [func(r[key]) for r in self.data if key in r]
def summarize(self, key: str, agg: str = "sum") -> Optional[Any]:
"""Aggregate a numeric key using different strategies."""
values = [r[key] for r in self.data if key in r]
if not values:
return None
if agg == "sum":
return sum(values)
if agg == "avg":
return sum(values) / len(values)
if agg == "max":
return max(values)
return None
def __len__(self) -> int:
"""Support len() for counting records."""
return len(self.data)
if __name__ == "__main__":
helper = DataHelper()
helper.add_record({"name": "Alice", "score": 90})
helper.add_record({"name": "Bob", "score": 75})
helper.add_record({"name": "Alice", "score": 85})
print("All records:", helper.data)
print("Filter by Alice:", helper.filter_by("name", "Alice"))
print("Scores doubled:", helper.transform("score", lambda x: x * 2))
print("Sum of scores:", helper.summarize("score", "sum"))
print("Average score:", helper.summarize("score", "avg"))
print("Number of records:", len(helper))
Output
All records: [{'name': 'Alice', 'score': 90}, {'name': 'Bob', 'score': 75}, {'name': 'Alice', 'score': 85}]
Filter by Alice: [{'name': 'Alice', 'score': 90}, {'name': 'Alice', 'score': 85}]
Scores doubled: [180, 150, 170]
Sum of scores: 250
Average score: 83.33333333333333
Number of records: 3
How it works
The DataHelper class uses a list of dictionaries to store records, making it easy to add, filter, and aggregate data. The add_record method follows the Command pattern by encapsulating the operation of appending a record. Filtering uses a simple Strategy pattern where the condition is passed as a key-value pair, and transformation applies a mapping function to a specific field. Aggregation methods (summarize) implement different strategies like sum, average, and max. The class also supports len() by implementing __len__, making it intuitive to count records.
Common mistakes
- Forgetting to use `.get(key, default)` instead of direct indexing, which can raise KeyError if a record lacks the field
- Assuming all records contain the aggregation key, leading to skipped values or errors
- Not handling empty datasets, resulting in ZeroDivisionError for average or None returns
Variations
- Use `defaultdict(list)` to automatically initialize missing keys
- Implement a more generic filter that accepts a lambda predicate instead of a simple key-value pair
Real-world use cases
- Building an in-memory data store for a small CLI application that needs basic CRUD and filter operations.
- Creating a lightweight analytics helper for aggregating metrics from log entries or event streams.
- Providing a simple wrapper around collected data for early prototyping before moving to a database.
Sponsored
More from System design patterns
- Build a BFF (Backend for Frontend) Mock Aggregator in Python medium
- Builder pattern for mocking complex objects in Python easy
- Circuit Breaker Pattern in Python: Closed, Open, and Half-Open States medium
- Create a Data Helper Class in Python easy
- Domain Driven Design Aggregate Root Example in Python medium
- Facade Pattern in Python with Mock Simplification medium
Keep learning
Related tutorials and quizzes for this topic.