Skip to main content
🔒 Preview mode. The first 15 Foundations lessons are free; this one is Pro. Start a 7-day trial to unlock the editor, AI hints and the rest of the curriculum. Card required, cancel any time in Dashboard.Start 7-day trial →
← CoursesSenior Deep-DivesModule 6 · FAANG-2026 deep divesdataclass field(default_factory) — the mutable-default blockpredict114 / 161
+150 XP
Task
📝 **Task:** Predict the exact output. (1) Try defining a dataclass \`Bad\` with \`items: list = []\` — catch the ValueError. (2) Define \`Good\` with \`field(default_factory=list)\`. (3) Create two instances, append to one's list, then print both lists + check identity. Does \`g2\` see the append? 📋 Implement the function above. Tests run automatically. 💡 **Hint:** Re-read the theory if you get stuck.
Predict the output

Read the code carefully

from dataclasses import dataclass, field


try:
    @dataclass
    class Bad:
        items: list = []
except ValueError as e:
    print(f"err:{e}")


@dataclass
class Good:
    items: list = field(default_factory=list)


g1 = Good()
g2 = Good()
g1.items.append(1)
print(g1.items)
print(g2.items)
print(g1.items is g2.items)

What will the program print? Write here:

💬 Discussion

Be the first to ask a question or share a tip.
Sign in to join the discussion. Reading is free.
Loading discussion…