How to Create a Data Formatter Class in Python

A beginner-friendly helper class to format lists, dictionaries, and stored records into readable strings.

Easy Python 3.6+ Aug 9, 2026 OOP & classes 12 views 0 copies

Python code

34 lines
Python 3.6+
class 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

stdout
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

  1. Use `dataclasses.dataclass` to define a record structure with type hints.
  2. 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

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.