How to Build a Simple Data Helper Class in Python
A beginner-friendly DataHelper class that stores Python dataclass objects as JSON records to disk, with load, add, and save methods.
Python code
41 linesimport json
from dataclasses import dataclass, asdict
from pathlib import Path
@dataclass
class User:
name: str
age: int
email: str
class DataHelper:
def __init__(self, filepath: str = "data.json"):
self.filepath = Path(filepath)
self._data = self._load()
def _load(self) -> list:
if self.filepath.exists():
with open(self.filepath, "r") as f:
return json.load(f)
return []
def save(self) -> None:
with open(self.filepath, "w") as f:
json.dump(self._data, f, indent=2)
print(f"Saved {len(self._data)} records to {self.filepath}")
def add(self, item: User) -> None:
self._data.append(asdict(item))
self.save()
def get_all(self) -> list:
return self._data
def main():
helper = DataHelper("users.json")
helper.add(User("Alice", 30, "alice@example.com"))
helper.add(User("Bob", 25, "bob@example.com"))
print("All users:", helper.get_all())
if __name__ == "__main__":
main()
Output
Saved 1 records to users.json
Saved 2 records to users.json
All users: [{'name': 'Alice', 'age': 30, 'email': 'alice@example.com'}, {'name': 'Bob', 'age': 25, 'email': 'bob@example.com'}]
How it works
The @dataclass decorator automatically generates __init__, __repr__, and other methods, keeping User clean and focused on data. asdict() converts each dataclass instance into a plain dictionary so it can be serialized with json.dump. The DataHelper loads existing data in __init__ via _load, so records accumulate across runs rather than resetting. Every add call immediately persists the whole list with save, keeping disk state in sync at the cost of rewriting the file each time. Using pathlib.Path makes file handling cross-platform and readable.
Common mistakes
- Forgetting that `json.load` reads from a file object, not a string — use `json.loads` for strings.
- Overwriting data because `_load` is never called when the file already exists.
- Serializing dataclass objects directly — you must convert them to dicts first with `asdict`.
- Ignoring `indent` in `json.dump`, which produces unreadable single-line JSON.
Variations
- Use `json.dumps` and `Path.write_text` to save without a context manager.
- Subclass `User` as a `TypedDict` and validate schema with Pydantic for stricter typing.
Real-world use cases
- Persisting user configuration or preferences in a small CLI tool without a database.
- Storing test fixtures or seed data for automated tests in a portable JSON file.
- Logging structured event records to disk in a lightweight dev environment before adding a full observability stack.
Sponsored
More from Production deployment patterns
- Auto Rollback on Error Rate Exceeded in Python medium
- Automate Semantic Versioning with Conventional Commits in Python medium
- Design a Data Helper for Beginners in Python easy
- Docker healthcheck CMD mock in Python easy
- Generate a Mock Artifact Version Tag in Python easy
- Generate a docker-compose.yml with mock services in Python easy
Keep learning
Related tutorials and quizzes for this topic.