Predict the output
What does the error body print?
import json
from dataclasses import asdict, dataclass, field
@dataclass
class Problem:
type: str
title: str
status: int
errors: list[dict[str, str]] = field(default_factory=list)
p = Problem("/problems/validation", "Invalid order", 422)
p.errors.append({"field": "qty", "reason": "must be > 0"})
print(json.dumps(asdict(p))[:58])Hint 1 of 1
What does asdict return?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A {"type": "/problems/validation", "title": "Invalid order",
Correct. asdict keeps field order and json.dumps writes it; the print shows the first 58 characters.
A dataclass keeps fields in declaration order, asdict turns it into a plain dict, and json.dumps writes the keys in that order. The slice just cuts the JSON string after 58 characters.
Why not the others?
- B
{"status": 422, "type": "/problems/validation", "title":. Fields keep their declaration order. - C
Problem(type='/problems/validation', title='Invalid order'. That's the repr, not JSON. - D A TypeError: dataclasses aren't JSON serializable. asdict converts it to a dict first.