Format data in Python using dataclasses like gRPC messages

Convert Python dataclasses to and from dicts and format them gRPC-style for clean data handling.

Easy Python 3.9+ Aug 9, 2026 API design & gRPC 14 views 0 copies

Python code

57 lines
Python 3.9+
from dataclasses import dataclass
from typing import Any, Dict, List, Optional


@dataclass
class ProductInfo:
    """Data class representing a gRPC-style product message."""

    name: str
    price: float
    tags: List[str]
    description: Optional[str] = None

    def to_dict(self) -> Dict[str, Any]:
        """Convert to plain dict (like gRPC message to Python dict)."""
        return {
            "name": self.name,
            "price": self.price,
            "tags": list(self.tags),
            "description": self.description,
        }

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "ProductInfo":
        """Create from dict (like parsing JSON into gRPC message)."""
        return cls(
            name=data["name"],
            price=float(data.get("price", 0.0)),
            tags=list(data.get("tags", [])),
            description=data.get("description"),
        )


def format_product_grpc_style(product: ProductInfo) -> str:
    """Format product like a gRPC debug string for beginners."""
    lines = [f"ProductInfo(name: {product.name}, price: {product.price})"]
    if product.description:
        lines.insert(0, f"# {product.description}")
    lines.append(f"  tags: {', '.join(product.tags) if product.tags else '(none)'}")
    return "\n".join(lines)


if __name__ == "__main__":
    # Simulate gRPC message round-trip using dicts
    raw_data = {
        "name": "Wireless Mouse",
        "price": 29.99,
        "tags": ["electronics", "computer"],
        "description": "Ergonomic 2.4GHz wireless mouse",
    }

    msg_dict = ProductInfo.from_dict(raw_data).to_dict()
    print("Dict (gRPC serialization):", msg_dict)

    product = ProductInfo.from_dict(msg_dict)
    print("\nFormatted output:")
    print(format_product_grpc_style(product))

Output

stdout
Dict (gRPC serialization): {'name': 'Wireless Mouse', 'price': 29.99, 'tags': ['electronics', 'computer'], 'description': 'Ergonomic 2.4GHz wireless mouse'}

Formatted output:
# Ergonomic 2.4GHz wireless mouse
ProductInfo(name: Wireless Mouse, price: 29.99)
  tags: electronics, computer

How it works

The ProductInfo dataclass encapsulates fields like a gRPC message. to_dict and from_dict simulate serialization and deserialization, mirroring protobuf conversion. The format_product_grpc_style function produces a human-readable debug string. This pattern keeps data handling consistent and beginner-friendly.

Common mistakes

  • Forgetting to handle missing keys in `from_dict` without defaults.
  • Assuming tags are always present, causing AttributeError.
  • Not converting types (e.g., price to float) when deserializing.

Variations

  1. Use `dataclasses.asdict` for built-in dict conversion.
  2. Add `__str__` to the dataclass for direct formatting.

Real-world use cases

  • Logging or debugging gRPC messages in development.
  • Converting API request payloads to internal models for validation.
  • Formatting structured data for display in CLI tools or dashboards.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from API design & gRPC

Related tutorials and quizzes for this topic.