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.
Python code
57 linesfrom 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
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
- Use `dataclasses.asdict` for built-in dict conversion.
- 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
More from API design & gRPC
- Build a Bulk Array POST Mock Server in Python medium
- Build a Mock REST API with PUT and GET in Python medium
- Convert Protobuf to JSON and Dict in Python easy
- Create a Data Helper in Python for gRPC-style APIs easy
- Generate an OpenAPI Spec from Mock Routes in Python easy
- How to Add HATEOAS Links to a Python API Response easy
Keep learning
Related tutorials and quizzes for this topic.