How to Create a Data Formatter Class in Python
A beginner-friendly helper class to format lists, dictionaries, and stored records into readable strings.
Python code
34 linesclass DataFormatter:
"""Helper class for beginners to format common data types."""
def __init__(self, name="data"):
self.name = name
self.records = []
def add_record(self, key, value):
"""Add a key-value record to the formatter."""
self.records.append({"key": key, "value": value})
return self
def format_list(self, items, separator=", "):
"""Format a list into a string with a custom separator."""
return separator.join(str(item) for item in items)
def format_dict(self, data):
"""Format a dictionary as 'key=value' pairs joined by '&'."""
return "&".join(f"{k}={v}" for k, v in data.items())
def summary(self):
"""Return a readable summary of all added records."""
lines = [f"{self.name} summary:"]
for record in self.records:
lines.append(f" {record['key']}: {record['value']}")
return "\n".join(lines)
if __name__ == "__main__":
formatter = DataFormatter("fruits")
formatter.add_record("count", 3).add_record("style", "fresh")
print(formatter.format_list(["apple", "banana", "cherry"]))
print(formatter.format_dict({"color": "red", "size": "medium"}))
print(formatter.summary())
Output
apple, banana, cherry
color=red&size=medium
fruits summary:
count: 3
style: fresh
How it works
The DataFormatter class stores records in a list of dictionaries, allowing chained calls via return self. format_list uses a generator expression to convert items to strings before joining, avoiding type errors. format_dict leverages f-strings to build query-like strings. The summary method iterates over stored records to produce a human-readable output. This pattern shows how a class can encapsulate multiple formatting utilities for reuse.
Common mistakes
- Forgetting to return `self` in `add_record` when chaining method calls.
- Not converting list items to strings, causing TypeError with mixed types.
- Using `.items()` without checking for empty dictionaries, which is safe but may surprise.
- Forgetting to instantiate with a meaningful name, giving generic output.
Variations
- Use `dataclasses.dataclass` to define a record structure with type hints.
- Use `str.join` with a list comprehension instead of generator for small lists.
Real-world use cases
- Generating query strings for API requests from dictionaries of parameters.
- Producing readable logs or console summaries from collected metrics.
- Formatting CSV rows from lists of values for export in data pipelines.
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.