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 10 · Production idioms (modern Python)@dataclass(kw_only=True, slots=True) — the modern senior defaultpredict143 / 161
+150 XP
Task
📝 **Task:** Predict the 5-line output. A User dataclass with kw_only=True + slots=True is constructed via keyword; positional construction is then attempted (rejected); attribute assignment outside slots is attempted (rejected). A separate Mix dataclass uses per-field kw_only to force `b` keyword while keeping `a` and `c` positional. 📋 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


@dataclass(kw_only=True, slots=True)
class User:
    id: int
    name: str
    email: str


u = User(id=42, name="Ada", email="ada@x.com")
print(u)
print(hasattr(u, "__dict__"))

try:
    User(42, "Ada", "ada@x.com")
except TypeError as e:
    print("positional rejected" if "positional" in str(e).lower() else "rejected")

try:
    u.extra = "no"
except AttributeError:
    print("attrs locked")


@dataclass
class Mix:
    a: int
    b: int = field(kw_only=True)
    c: int = 0


m = Mix(1, c=3, b=2)
print(m)

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…