Small Group Tutorials

Here to help students catch up, keep up, and move ahead. Book a consultation here.

How to Master Python Dataclasses in Punggol Tuition

A student with short hair sits on a low stone ledge holding a Mathematics textbook, with a white backpack beside her.

When a learner can reproduce a familiar example but a small variation causes confusion, the problem is usually an incomplete model rather than a lack of effort. The fastest useful response is to expose the hidden state and test one boundary at a time.

A Python dataclass is a class whose annotated fields drive generated methods such as __init__(), __repr__() and __eq__(). The important learning job is to predict exactly which fields participate in each generated behaviour, where mutability enters, and when a plain class would state the design more honestly. This guide begins with that mechanism, then develops it through worked traces, deliberate mistakes, explained practice and transfer decisions.

The aim is independent reasoning. A learner should be able to predict behaviour, locate the earliest wrong assumption, use a safe diagnostic procedure and defend a design choice in a new project.

Punggol families can use the guide in short sessions around homework, CCAs and rest. The activities are proposed learning exercises, not claims about a physical branch, timetable, class size, fee, school relationship or guaranteed result.

Use disposable data and repositories, preserve backups, and check version-sensitive details against the official source. Current documentation settles a technical contract; observation and explanation turn that contract into usable knowledge.

Find your next learning step

Choose the route that matches the present difficulty. Use the complete index for a systematic course.

Build the model

Chapters 1-4 . Begin here, then continue after the learner can predict, verify and explain.

Use the core tools

Chapters 5-8 . Begin here, then continue after the learner can predict, verify and explain.

Handle boundaries

Chapters 9-12 . Begin here, then continue after the learner can predict, verify and explain.

Debug and verify

Chapters 13-16 . Begin here, then continue after the learner can predict, verify and explain.

Transfer with judgment

Chapters 17-20 . Begin here, then continue after the learner can predict, verify and explain.

Open the full chapter index . Jump to capstone practice . Use the How Studying Works hub . Read the official documentation

CHAPTER 1 OF 20 . Build the model

1. The generated-method mental model

Back to contents

The decorator reads annotated fields and may generate methods on the same class; it does not turn data into a dictionary or perform runtime type validation. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.

The high-value mistake in this chapter is expecting the annotation to reject a value of the wrong runtime type. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Inspect the generated signature and compare repr and equality on two tiny instances.

Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.

Core worked example

@dataclass
class Task:
    name: str
    done: bool = False

Explained result. Task(‘Read’) accepts name and supplies done=False; the annotation documents intent but does not itself enforce str. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: assignment record. Predict the rule using subject, due date, status and an optional note. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “The decorator reads annotated fields and may generate methods on the same class; it does not turn data into a dictionary or perform runtime type validation.” Apply this procedure: Inspect the generated signature and compare repr and equality on two tiny instances. The expected mechanism is: Task(‘Read’) accepts name and supplies done=False; the annotation documents intent but does not itself enforce str. For the assignment record, add one near-miss that exposes expecting the annotation to reject a value of the wrong runtime type. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: library book. Contrast the rule using title, call number, loan state and borrower. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “The decorator reads annotated fields and may generate methods on the same class; it does not turn data into a dictionary or perform runtime type validation.” Apply this procedure: Inspect the generated signature and compare repr and equality on two tiny instances. The expected mechanism is: Task(‘Read’) accepts name and supplies done=False; the annotation documents intent but does not itself enforce str. For the library book, add one near-miss that exposes expecting the annotation to reject a value of the wrong runtime type. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: CCA registration. Stress-test the rule using activity, weekday, capacity and participant list. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “The decorator reads annotated fields and may generate methods on the same class; it does not turn data into a dictionary or perform runtime type validation.” Apply this procedure: Inspect the generated signature and compare repr and equality on two tiny instances. The expected mechanism is: Task(‘Read’) accepts name and supplies done=False; the annotation documents intent but does not itself enforce str. For the CCA registration, add one near-miss that exposes expecting the annotation to reject a value of the wrong runtime type. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: science reading. Explain the rule using quantity, unit, uncertainty and observation. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “The decorator reads annotated fields and may generate methods on the same class; it does not turn data into a dictionary or perform runtime type validation.” Apply this procedure: Inspect the generated signature and compare repr and equality on two tiny instances. The expected mechanism is: Task(‘Read’) accepts name and supplies done=False; the annotation documents intent but does not itself enforce str. For the science reading, add one near-miss that exposes expecting the annotation to reject a value of the wrong runtime type. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Diagnostic route

  • Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
  • Boundary check: create the smallest input that triggers expecting the annotation to reject a value of the wrong runtime type.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Inspect the generated signature and compare repr and equality on two tiny instances.” and record the first changed observation.
  • Transfer check: repeat the rule in a second context and identify what remains invariant.

A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.

Practice with an explained answer

Question. Build a tiny budget item with label, unit cost, quantity and category. Include one ordinary case, one boundary and one deliberate failure caused by expecting the annotation to reject a value of the wrong runtime type. Predict each result before using a tool, then report the first point where observation differs from prediction.

Answer guide. A strong response starts with the rule: The decorator reads annotated fields and may generate methods on the same class; it does not turn data into a dictionary or perform runtime type validation. It shows a trace, not only a final value. The ordinary case should demonstrate “Task(‘Read’) accepts name and supplies done=False; the annotation documents intent but does not itself enforce str.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Inspect the generated signature and compare repr and equality on two tiny instances. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.

Previous chapter . Contents . Next chapter

CHAPTER 2 OF 20 . Build the model

2. Field order and constructor order

Back to contents

Field declaration order determines parameter order and participates in generated repr, equality and ordering behaviour. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.

The high-value mistake in this chapter is rearranging fields as a cosmetic edit when callers use positional arguments. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Prefer clear field order and keyword calls at boundaries; inspect the signature after refactoring.

Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.

Core worked example

@dataclass
class Point:
    x: float
    y: float

Explained result. Point(2, 5) binds x=2 and y=5 because declaration order drives the generated constructor. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: CCA registration. Contrast the rule using activity, weekday, capacity and participant list. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “Field declaration order determines parameter order and participates in generated repr, equality and ordering behaviour.” Apply this procedure: Prefer clear field order and keyword calls at boundaries; inspect the signature after refactoring. The expected mechanism is: Point(2, 5) binds x=2 and y=5 because declaration order drives the generated constructor. For the CCA registration, add one near-miss that exposes rearranging fields as a cosmetic edit when callers use positional arguments. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: science reading. Stress-test the rule using quantity, unit, uncertainty and observation. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “Field declaration order determines parameter order and participates in generated repr, equality and ordering behaviour.” Apply this procedure: Prefer clear field order and keyword calls at boundaries; inspect the signature after refactoring. The expected mechanism is: Point(2, 5) binds x=2 and y=5 because declaration order drives the generated constructor. For the science reading, add one near-miss that exposes rearranging fields as a cosmetic edit when callers use positional arguments. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: revision card. Explain the rule using topic, confidence, evidence and next review date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “Field declaration order determines parameter order and participates in generated repr, equality and ordering behaviour.” Apply this procedure: Prefer clear field order and keyword calls at boundaries; inspect the signature after refactoring. The expected mechanism is: Point(2, 5) binds x=2 and y=5 because declaration order drives the generated constructor. For the revision card, add one near-miss that exposes rearranging fields as a cosmetic edit when callers use positional arguments. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: budget item. Transfer the rule using label, unit cost, quantity and category. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “Field declaration order determines parameter order and participates in generated repr, equality and ordering behaviour.” Apply this procedure: Prefer clear field order and keyword calls at boundaries; inspect the signature after refactoring. The expected mechanism is: Point(2, 5) binds x=2 and y=5 because declaration order drives the generated constructor. For the budget item, add one near-miss that exposes rearranging fields as a cosmetic edit when callers use positional arguments. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Diagnostic route

  • Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
  • Boundary check: create the smallest input that triggers rearranging fields as a cosmetic edit when callers use positional arguments.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Prefer clear field order and keyword calls at boundaries; inspect the signature after refactoring.” and record the first changed observation.
  • Transfer check: repeat the rule in a second context and identify what remains invariant.

A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.

Practice with an explained answer

Question. Build a tiny transport leg with start, end, minutes and fare. Include one ordinary case, one boundary and one deliberate failure caused by rearranging fields as a cosmetic edit when callers use positional arguments. Predict each result before using a tool, then report the first point where observation differs from prediction.

Answer guide. A strong response starts with the rule: Field declaration order determines parameter order and participates in generated repr, equality and ordering behaviour. It shows a trace, not only a final value. The ordinary case should demonstrate “Point(2, 5) binds x=2 and y=5 because declaration order drives the generated constructor.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Prefer clear field order and keyword calls at boundaries; inspect the signature after refactoring. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.

Previous chapter . Contents . Next chapter

CHAPTER 3 OF 20 . Build the model

3. Required fields and defaults

Back to contents

A field without a default must precede fields with defaults, including across dataclass inheritance. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.

The high-value mistake in this chapter is placing a required field after a default and treating the resulting TypeError as mysterious. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Partition fields into required and optional, then verify the combined inherited order.

Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.

Core worked example

@dataclass
class Quiz:
    topic: str
    attempts: int = 0

Explained result. topic is required; attempts may be omitted and receives zero. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: revision card. Stress-test the rule using topic, confidence, evidence and next review date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “A field without a default must precede fields with defaults, including across dataclass inheritance.” Apply this procedure: Partition fields into required and optional, then verify the combined inherited order. The expected mechanism is: topic is required; attempts may be omitted and receives zero. For the revision card, add one near-miss that exposes placing a required field after a default and treating the resulting TypeError as mysterious. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: budget item. Explain the rule using label, unit cost, quantity and category. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “A field without a default must precede fields with defaults, including across dataclass inheritance.” Apply this procedure: Partition fields into required and optional, then verify the combined inherited order. The expected mechanism is: topic is required; attempts may be omitted and receives zero. For the budget item, add one near-miss that exposes placing a required field after a default and treating the resulting TypeError as mysterious. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: transport leg. Transfer the rule using start, end, minutes and fare. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “A field without a default must precede fields with defaults, including across dataclass inheritance.” Apply this procedure: Partition fields into required and optional, then verify the combined inherited order. The expected mechanism is: topic is required; attempts may be omitted and receives zero. For the transport leg, add one near-miss that exposes placing a required field after a default and treating the resulting TypeError as mysterious. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: project task. Predict the rule using owner, priority, state and dependencies. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “A field without a default must precede fields with defaults, including across dataclass inheritance.” Apply this procedure: Partition fields into required and optional, then verify the combined inherited order. The expected mechanism is: topic is required; attempts may be omitted and receives zero. For the project task, add one near-miss that exposes placing a required field after a default and treating the resulting TypeError as mysterious. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Diagnostic route

  • Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
  • Boundary check: create the smallest input that triggers placing a required field after a default and treating the resulting TypeError as mysterious.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Partition fields into required and optional, then verify the combined inherited order.” and record the first changed observation.
  • Transfer check: repeat the rule in a second context and identify what remains invariant.

A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.

Practice with an explained answer

Question. Build a tiny project task with owner, priority, state and dependencies. Include one ordinary case, one boundary and one deliberate failure caused by placing a required field after a default and treating the resulting TypeError as mysterious. Predict each result before using a tool, then report the first point where observation differs from prediction.

Answer guide. A strong response starts with the rule: A field without a default must precede fields with defaults, including across dataclass inheritance. It shows a trace, not only a final value. The ordinary case should demonstrate “topic is required; attempts may be omitted and receives zero.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Partition fields into required and optional, then verify the combined inherited order. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.

Previous chapter . Contents . Next chapter

CHAPTER 4 OF 20 . Build the model

4. default_factory and mutable values

Back to contents

default_factory calls a zero-argument function for each new instance, preventing accidental sharing of mutable defaults. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.

The high-value mistake in this chapter is using one list object as a class-level default for every instance. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Create two instances, mutate one collection and prove the other is independent.

Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.

Core worked example

@dataclass
class Plan:
    tasks: list[str] = field(default_factory=list)

Explained result. Each Plan receives a distinct list, so adding to one plan does not modify another. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: transport leg. Explain the rule using start, end, minutes and fare. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “default_factory calls a zero-argument function for each new instance, preventing accidental sharing of mutable defaults.” Apply this procedure: Create two instances, mutate one collection and prove the other is independent. The expected mechanism is: Each Plan receives a distinct list, so adding to one plan does not modify another. For the transport leg, add one near-miss that exposes using one list object as a class-level default for every instance. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: project task. Transfer the rule using owner, priority, state and dependencies. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “default_factory calls a zero-argument function for each new instance, preventing accidental sharing of mutable defaults.” Apply this procedure: Create two instances, mutate one collection and prove the other is independent. The expected mechanism is: Each Plan receives a distinct list, so adding to one plan does not modify another. For the project task, add one near-miss that exposes using one list object as a class-level default for every instance. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: assignment record. Predict the rule using subject, due date, status and an optional note. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “default_factory calls a zero-argument function for each new instance, preventing accidental sharing of mutable defaults.” Apply this procedure: Create two instances, mutate one collection and prove the other is independent. The expected mechanism is: Each Plan receives a distinct list, so adding to one plan does not modify another. For the assignment record, add one near-miss that exposes using one list object as a class-level default for every instance. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: library book. Contrast the rule using title, call number, loan state and borrower. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “default_factory calls a zero-argument function for each new instance, preventing accidental sharing of mutable defaults.” Apply this procedure: Create two instances, mutate one collection and prove the other is independent. The expected mechanism is: Each Plan receives a distinct list, so adding to one plan does not modify another. For the library book, add one near-miss that exposes using one list object as a class-level default for every instance. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Diagnostic route

  • Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
  • Boundary check: create the smallest input that triggers using one list object as a class-level default for every instance.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Create two instances, mutate one collection and prove the other is independent.” and record the first changed observation.
  • Transfer check: repeat the rule in a second context and identify what remains invariant.

A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.

Practice with an explained answer

Question. Build a tiny assignment record with subject, due date, status and an optional note. Include one ordinary case, one boundary and one deliberate failure caused by using one list object as a class-level default for every instance. Predict each result before using a tool, then report the first point where observation differs from prediction.

Answer guide. A strong response starts with the rule: default_factory calls a zero-argument function for each new instance, preventing accidental sharing of mutable defaults. It shows a trace, not only a final value. The ordinary case should demonstrate “Each Plan receives a distinct list, so adding to one plan does not modify another.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Create two instances, mutate one collection and prove the other is independent. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.

Previous chapter . Contents . Next chapter

CHAPTER 5 OF 20 . Use the core tools

5. field() controls

Back to contents

field() can control constructor inclusion, repr visibility, comparison, hashing, metadata and keyword-only behaviour per field. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.

The high-value mistake in this chapter is hiding a field from repr and assuming it is also excluded from equality. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Write a table of each flag and test one pair of instances that differs only in that field.

Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.

Core worked example

token: str = field(repr=False, compare=False)

Explained result. The token is omitted from repr and equality because both policies are stated separately. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: assignment record. Transfer the rule using subject, due date, status and an optional note. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “field() can control constructor inclusion, repr visibility, comparison, hashing, metadata and keyword-only behaviour per field.” Apply this procedure: Write a table of each flag and test one pair of instances that differs only in that field. The expected mechanism is: The token is omitted from repr and equality because both policies are stated separately. For the assignment record, add one near-miss that exposes hiding a field from repr and assuming it is also excluded from equality. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: library book. Predict the rule using title, call number, loan state and borrower. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “field() can control constructor inclusion, repr visibility, comparison, hashing, metadata and keyword-only behaviour per field.” Apply this procedure: Write a table of each flag and test one pair of instances that differs only in that field. The expected mechanism is: The token is omitted from repr and equality because both policies are stated separately. For the library book, add one near-miss that exposes hiding a field from repr and assuming it is also excluded from equality. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: CCA registration. Contrast the rule using activity, weekday, capacity and participant list. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “field() can control constructor inclusion, repr visibility, comparison, hashing, metadata and keyword-only behaviour per field.” Apply this procedure: Write a table of each flag and test one pair of instances that differs only in that field. The expected mechanism is: The token is omitted from repr and equality because both policies are stated separately. For the CCA registration, add one near-miss that exposes hiding a field from repr and assuming it is also excluded from equality. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: science reading. Stress-test the rule using quantity, unit, uncertainty and observation. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “field() can control constructor inclusion, repr visibility, comparison, hashing, metadata and keyword-only behaviour per field.” Apply this procedure: Write a table of each flag and test one pair of instances that differs only in that field. The expected mechanism is: The token is omitted from repr and equality because both policies are stated separately. For the science reading, add one near-miss that exposes hiding a field from repr and assuming it is also excluded from equality. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Diagnostic route

  • Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
  • Boundary check: create the smallest input that triggers hiding a field from repr and assuming it is also excluded from equality.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Write a table of each flag and test one pair of instances that differs only in that field.” and record the first changed observation.
  • Transfer check: repeat the rule in a second context and identify what remains invariant.

A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.

Practice with an explained answer

Question. Build a tiny library book with title, call number, loan state and borrower. Include one ordinary case, one boundary and one deliberate failure caused by hiding a field from repr and assuming it is also excluded from equality. Predict each result before using a tool, then report the first point where observation differs from prediction.

Answer guide. A strong response starts with the rule: field() can control constructor inclusion, repr visibility, comparison, hashing, metadata and keyword-only behaviour per field. It shows a trace, not only a final value. The ordinary case should demonstrate “The token is omitted from repr and equality because both policies are stated separately.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Write a table of each flag and test one pair of instances that differs only in that field. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.

Previous chapter . Contents . Next chapter

CHAPTER 6 OF 20 . Use the core tools

6. Equality and identical types

Back to contents

Generated equality compares participating fields in order and requires the other instance to have the identical type. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.

The high-value mistake in this chapter is assuming two different dataclass types with the same values are equal. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Compare same-type and cross-type instances and identify the type guard.

Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.

Core worked example

@dataclass
class Metres: value: int
@dataclass
class Seconds: value: int

Explained result. Metres(3) is not equal to Seconds(3), even though both expose value=3. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: CCA registration. Predict the rule using activity, weekday, capacity and participant list. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “Generated equality compares participating fields in order and requires the other instance to have the identical type.” Apply this procedure: Compare same-type and cross-type instances and identify the type guard. The expected mechanism is: Metres(3) is not equal to Seconds(3), even though both expose value=3. For the CCA registration, add one near-miss that exposes assuming two different dataclass types with the same values are equal. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: science reading. Contrast the rule using quantity, unit, uncertainty and observation. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “Generated equality compares participating fields in order and requires the other instance to have the identical type.” Apply this procedure: Compare same-type and cross-type instances and identify the type guard. The expected mechanism is: Metres(3) is not equal to Seconds(3), even though both expose value=3. For the science reading, add one near-miss that exposes assuming two different dataclass types with the same values are equal. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: revision card. Stress-test the rule using topic, confidence, evidence and next review date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “Generated equality compares participating fields in order and requires the other instance to have the identical type.” Apply this procedure: Compare same-type and cross-type instances and identify the type guard. The expected mechanism is: Metres(3) is not equal to Seconds(3), even though both expose value=3. For the revision card, add one near-miss that exposes assuming two different dataclass types with the same values are equal. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: budget item. Explain the rule using label, unit cost, quantity and category. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “Generated equality compares participating fields in order and requires the other instance to have the identical type.” Apply this procedure: Compare same-type and cross-type instances and identify the type guard. The expected mechanism is: Metres(3) is not equal to Seconds(3), even though both expose value=3. For the budget item, add one near-miss that exposes assuming two different dataclass types with the same values are equal. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Diagnostic route

  • Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
  • Boundary check: create the smallest input that triggers assuming two different dataclass types with the same values are equal.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Compare same-type and cross-type instances and identify the type guard.” and record the first changed observation.
  • Transfer check: repeat the rule in a second context and identify what remains invariant.

A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.

Practice with an explained answer

Question. Build a tiny CCA registration with activity, weekday, capacity and participant list. Include one ordinary case, one boundary and one deliberate failure caused by assuming two different dataclass types with the same values are equal. Predict each result before using a tool, then report the first point where observation differs from prediction.

Answer guide. A strong response starts with the rule: Generated equality compares participating fields in order and requires the other instance to have the identical type. It shows a trace, not only a final value. The ordinary case should demonstrate “Metres(3) is not equal to Seconds(3), even though both expose value=3.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Compare same-type and cross-type instances and identify the type guard. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.

Previous chapter . Contents . Next chapter

CHAPTER 7 OF 20 . Use the core tools

7. Ordering is tuple-like

Back to contents

order=True generates rich comparisons from participating fields in declaration order, provided equality is enabled. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.

The high-value mistake in this chapter is sorting by the field a reader notices rather than the first comparable field. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. State the sort key implied by field order, then compare it with an explicit key function.

Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.

Core worked example

@dataclass(order=True)
class Result:
    score: int
    name: str

Explained result. Results sort by score first and use name only when scores tie. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: revision card. Contrast the rule using topic, confidence, evidence and next review date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “order=True generates rich comparisons from participating fields in declaration order, provided equality is enabled.” Apply this procedure: State the sort key implied by field order, then compare it with an explicit key function. The expected mechanism is: Results sort by score first and use name only when scores tie. For the revision card, add one near-miss that exposes sorting by the field a reader notices rather than the first comparable field. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: budget item. Stress-test the rule using label, unit cost, quantity and category. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “order=True generates rich comparisons from participating fields in declaration order, provided equality is enabled.” Apply this procedure: State the sort key implied by field order, then compare it with an explicit key function. The expected mechanism is: Results sort by score first and use name only when scores tie. For the budget item, add one near-miss that exposes sorting by the field a reader notices rather than the first comparable field. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: transport leg. Explain the rule using start, end, minutes and fare. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “order=True generates rich comparisons from participating fields in declaration order, provided equality is enabled.” Apply this procedure: State the sort key implied by field order, then compare it with an explicit key function. The expected mechanism is: Results sort by score first and use name only when scores tie. For the transport leg, add one near-miss that exposes sorting by the field a reader notices rather than the first comparable field. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: project task. Transfer the rule using owner, priority, state and dependencies. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “order=True generates rich comparisons from participating fields in declaration order, provided equality is enabled.” Apply this procedure: State the sort key implied by field order, then compare it with an explicit key function. The expected mechanism is: Results sort by score first and use name only when scores tie. For the project task, add one near-miss that exposes sorting by the field a reader notices rather than the first comparable field. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Diagnostic route

  • Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
  • Boundary check: create the smallest input that triggers sorting by the field a reader notices rather than the first comparable field.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “State the sort key implied by field order, then compare it with an explicit key function.” and record the first changed observation.
  • Transfer check: repeat the rule in a second context and identify what remains invariant.

A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.

Practice with an explained answer

Question. Build a tiny science reading with quantity, unit, uncertainty and observation. Include one ordinary case, one boundary and one deliberate failure caused by sorting by the field a reader notices rather than the first comparable field. Predict each result before using a tool, then report the first point where observation differs from prediction.

Answer guide. A strong response starts with the rule: order=True generates rich comparisons from participating fields in declaration order, provided equality is enabled. It shows a trace, not only a final value. The ordinary case should demonstrate “Results sort by score first and use name only when scores tie.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: State the sort key implied by field order, then compare it with an explicit key function. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.

Previous chapter . Contents . Next chapter

CHAPTER 8 OF 20 . Use the core tools

8. The equality, frozen and hash matrix

Back to contents

Hash generation depends on equality and frozen settings because hashable objects must not change in ways that alter equality. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.

The high-value mistake in this chapter is forcing unsafe_hash without protecting mutable equality fields. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Predict __hash__ for each flag combination and test set membership only after the model is stable.

Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.

Core worked example

@dataclass(frozen=True)
class Key:
    code: str

Explained result. With the default equality and frozen=True, a safe value-based hash is generated. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: transport leg. Stress-test the rule using start, end, minutes and fare. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “Hash generation depends on equality and frozen settings because hashable objects must not change in ways that alter equality.” Apply this procedure: Predict __hash__ for each flag combination and test set membership only after the model is stable. The expected mechanism is: With the default equality and frozen=True, a safe value-based hash is generated. For the transport leg, add one near-miss that exposes forcing unsafe_hash without protecting mutable equality fields. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: project task. Explain the rule using owner, priority, state and dependencies. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “Hash generation depends on equality and frozen settings because hashable objects must not change in ways that alter equality.” Apply this procedure: Predict __hash__ for each flag combination and test set membership only after the model is stable. The expected mechanism is: With the default equality and frozen=True, a safe value-based hash is generated. For the project task, add one near-miss that exposes forcing unsafe_hash without protecting mutable equality fields. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: assignment record. Transfer the rule using subject, due date, status and an optional note. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “Hash generation depends on equality and frozen settings because hashable objects must not change in ways that alter equality.” Apply this procedure: Predict __hash__ for each flag combination and test set membership only after the model is stable. The expected mechanism is: With the default equality and frozen=True, a safe value-based hash is generated. For the assignment record, add one near-miss that exposes forcing unsafe_hash without protecting mutable equality fields. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: library book. Predict the rule using title, call number, loan state and borrower. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “Hash generation depends on equality and frozen settings because hashable objects must not change in ways that alter equality.” Apply this procedure: Predict __hash__ for each flag combination and test set membership only after the model is stable. The expected mechanism is: With the default equality and frozen=True, a safe value-based hash is generated. For the library book, add one near-miss that exposes forcing unsafe_hash without protecting mutable equality fields. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Diagnostic route

  • Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
  • Boundary check: create the smallest input that triggers forcing unsafe_hash without protecting mutable equality fields.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Predict __hash__ for each flag combination and test set membership only after the model is stable.” and record the first changed observation.
  • Transfer check: repeat the rule in a second context and identify what remains invariant.

A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.

Practice with an explained answer

Question. Build a tiny revision card with topic, confidence, evidence and next review date. Include one ordinary case, one boundary and one deliberate failure caused by forcing unsafe_hash without protecting mutable equality fields. Predict each result before using a tool, then report the first point where observation differs from prediction.

Answer guide. A strong response starts with the rule: Hash generation depends on equality and frozen settings because hashable objects must not change in ways that alter equality. It shows a trace, not only a final value. The ordinary case should demonstrate “With the default equality and frozen=True, a safe value-based hash is generated.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Predict __hash__ for each flag combination and test set membership only after the model is stable. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.

Previous chapter . Contents . Next chapter

CHAPTER 9 OF 20 . Handle boundaries

9. Frozen is controlled mutation, not deep immutability

Back to contents

frozen=True blocks normal field assignment but does not recursively freeze a list or other mutable object stored in a field. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.

The high-value mistake in this chapter is placing a mutable list inside a frozen dataclass and calling the whole object immutable. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Use immutable field types or defensive copying when deep immutability matters.

Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.

Core worked example

@dataclass(frozen=True)
class Team:
    members: tuple[str, ...]

Explained result. A tuple supports the intended immutable value model more honestly than a list inside a frozen shell. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: assignment record. Explain the rule using subject, due date, status and an optional note. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “frozen=True blocks normal field assignment but does not recursively freeze a list or other mutable object stored in a field.” Apply this procedure: Use immutable field types or defensive copying when deep immutability matters. The expected mechanism is: A tuple supports the intended immutable value model more honestly than a list inside a frozen shell. For the assignment record, add one near-miss that exposes placing a mutable list inside a frozen dataclass and calling the whole object immutable. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: library book. Transfer the rule using title, call number, loan state and borrower. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “frozen=True blocks normal field assignment but does not recursively freeze a list or other mutable object stored in a field.” Apply this procedure: Use immutable field types or defensive copying when deep immutability matters. The expected mechanism is: A tuple supports the intended immutable value model more honestly than a list inside a frozen shell. For the library book, add one near-miss that exposes placing a mutable list inside a frozen dataclass and calling the whole object immutable. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: CCA registration. Predict the rule using activity, weekday, capacity and participant list. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “frozen=True blocks normal field assignment but does not recursively freeze a list or other mutable object stored in a field.” Apply this procedure: Use immutable field types or defensive copying when deep immutability matters. The expected mechanism is: A tuple supports the intended immutable value model more honestly than a list inside a frozen shell. For the CCA registration, add one near-miss that exposes placing a mutable list inside a frozen dataclass and calling the whole object immutable. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: science reading. Contrast the rule using quantity, unit, uncertainty and observation. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “frozen=True blocks normal field assignment but does not recursively freeze a list or other mutable object stored in a field.” Apply this procedure: Use immutable field types or defensive copying when deep immutability matters. The expected mechanism is: A tuple supports the intended immutable value model more honestly than a list inside a frozen shell. For the science reading, add one near-miss that exposes placing a mutable list inside a frozen dataclass and calling the whole object immutable. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Diagnostic route

  • Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
  • Boundary check: create the smallest input that triggers placing a mutable list inside a frozen dataclass and calling the whole object immutable.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Use immutable field types or defensive copying when deep immutability matters.” and record the first changed observation.
  • Transfer check: repeat the rule in a second context and identify what remains invariant.

A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.

Practice with an explained answer

Question. Build a tiny budget item with label, unit cost, quantity and category. Include one ordinary case, one boundary and one deliberate failure caused by placing a mutable list inside a frozen dataclass and calling the whole object immutable. Predict each result before using a tool, then report the first point where observation differs from prediction.

Answer guide. A strong response starts with the rule: frozen=True blocks normal field assignment but does not recursively freeze a list or other mutable object stored in a field. It shows a trace, not only a final value. The ordinary case should demonstrate “A tuple supports the intended immutable value model more honestly than a list inside a frozen shell.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Use immutable field types or defensive copying when deep immutability matters. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.

Previous chapter . Contents . Next chapter

CHAPTER 10 OF 20 . Handle boundaries

10. __post_init__ and invariants

Back to contents

The generated __init__ calls __post_init__ so related fields can be validated or derived after assignment. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.

The high-value mistake in this chapter is silently repairing invalid data when the caller needs a clear error. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. State each invariant, raise a precise exception and test every boundary.

Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.

Core worked example

def __post_init__(self):
    if self.end < self.start:
        raise ValueError('end before start')

Explained result. Construction fails at the domain boundary instead of allowing an impossible interval. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: CCA registration. Transfer the rule using activity, weekday, capacity and participant list. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “The generated __init__ calls __post_init__ so related fields can be validated or derived after assignment.” Apply this procedure: State each invariant, raise a precise exception and test every boundary. The expected mechanism is: Construction fails at the domain boundary instead of allowing an impossible interval. For the CCA registration, add one near-miss that exposes silently repairing invalid data when the caller needs a clear error. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: science reading. Predict the rule using quantity, unit, uncertainty and observation. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “The generated __init__ calls __post_init__ so related fields can be validated or derived after assignment.” Apply this procedure: State each invariant, raise a precise exception and test every boundary. The expected mechanism is: Construction fails at the domain boundary instead of allowing an impossible interval. For the science reading, add one near-miss that exposes silently repairing invalid data when the caller needs a clear error. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: revision card. Contrast the rule using topic, confidence, evidence and next review date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “The generated __init__ calls __post_init__ so related fields can be validated or derived after assignment.” Apply this procedure: State each invariant, raise a precise exception and test every boundary. The expected mechanism is: Construction fails at the domain boundary instead of allowing an impossible interval. For the revision card, add one near-miss that exposes silently repairing invalid data when the caller needs a clear error. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: budget item. Stress-test the rule using label, unit cost, quantity and category. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “The generated __init__ calls __post_init__ so related fields can be validated or derived after assignment.” Apply this procedure: State each invariant, raise a precise exception and test every boundary. The expected mechanism is: Construction fails at the domain boundary instead of allowing an impossible interval. For the budget item, add one near-miss that exposes silently repairing invalid data when the caller needs a clear error. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Diagnostic route

  • Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
  • Boundary check: create the smallest input that triggers silently repairing invalid data when the caller needs a clear error.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “State each invariant, raise a precise exception and test every boundary.” and record the first changed observation.
  • Transfer check: repeat the rule in a second context and identify what remains invariant.

A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.

Practice with an explained answer

Question. Build a tiny transport leg with start, end, minutes and fare. Include one ordinary case, one boundary and one deliberate failure caused by silently repairing invalid data when the caller needs a clear error. Predict each result before using a tool, then report the first point where observation differs from prediction.

Answer guide. A strong response starts with the rule: The generated __init__ calls __post_init__ so related fields can be validated or derived after assignment. It shows a trace, not only a final value. The ordinary case should demonstrate “Construction fails at the domain boundary instead of allowing an impossible interval.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: State each invariant, raise a precise exception and test every boundary. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.

Previous chapter . Contents . Next chapter

CHAPTER 11 OF 20 . Handle boundaries

11. InitVar for construction-only input

Back to contents

InitVar values enter the generated constructor and __post_init__ but are not stored as ordinary dataclass fields. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.

The high-value mistake in this chapter is using InitVar for information that later methods still need. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Separate transient construction help from lasting object state before choosing InitVar.

Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.

Core worked example

database: InitVar[Lookup | None] = None

Explained result. database can help compute a stored field during post-init without becoming part of fields() or repr. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: revision card. Predict the rule using topic, confidence, evidence and next review date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “InitVar values enter the generated constructor and __post_init__ but are not stored as ordinary dataclass fields.” Apply this procedure: Separate transient construction help from lasting object state before choosing InitVar. The expected mechanism is: database can help compute a stored field during post-init without becoming part of fields() or repr. For the revision card, add one near-miss that exposes using InitVar for information that later methods still need. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: budget item. Contrast the rule using label, unit cost, quantity and category. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “InitVar values enter the generated constructor and __post_init__ but are not stored as ordinary dataclass fields.” Apply this procedure: Separate transient construction help from lasting object state before choosing InitVar. The expected mechanism is: database can help compute a stored field during post-init without becoming part of fields() or repr. For the budget item, add one near-miss that exposes using InitVar for information that later methods still need. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: transport leg. Stress-test the rule using start, end, minutes and fare. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “InitVar values enter the generated constructor and __post_init__ but are not stored as ordinary dataclass fields.” Apply this procedure: Separate transient construction help from lasting object state before choosing InitVar. The expected mechanism is: database can help compute a stored field during post-init without becoming part of fields() or repr. For the transport leg, add one near-miss that exposes using InitVar for information that later methods still need. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: project task. Explain the rule using owner, priority, state and dependencies. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “InitVar values enter the generated constructor and __post_init__ but are not stored as ordinary dataclass fields.” Apply this procedure: Separate transient construction help from lasting object state before choosing InitVar. The expected mechanism is: database can help compute a stored field during post-init without becoming part of fields() or repr. For the project task, add one near-miss that exposes using InitVar for information that later methods still need. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Diagnostic route

  • Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
  • Boundary check: create the smallest input that triggers using InitVar for information that later methods still need.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Separate transient construction help from lasting object state before choosing InitVar.” and record the first changed observation.
  • Transfer check: repeat the rule in a second context and identify what remains invariant.

A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.

Practice with an explained answer

Question. Build a tiny project task with owner, priority, state and dependencies. Include one ordinary case, one boundary and one deliberate failure caused by using InitVar for information that later methods still need. Predict each result before using a tool, then report the first point where observation differs from prediction.

Answer guide. A strong response starts with the rule: InitVar values enter the generated constructor and __post_init__ but are not stored as ordinary dataclass fields. It shows a trace, not only a final value. The ordinary case should demonstrate “database can help compute a stored field during post-init without becoming part of fields() or repr.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Separate transient construction help from lasting object state before choosing InitVar. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.

Previous chapter . Contents . Next chapter

CHAPTER 12 OF 20 . Handle boundaries

12. ClassVar and shared class state

Back to contents

ClassVar annotations mark names that are not dataclass fields and therefore do not enter generated instance methods. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.

The high-value mistake in this chapter is forgetting ClassVar and accidentally exposing a shared constant as constructor data. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Inspect fields() and the generated signature to confirm the boundary.

Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.

Core worked example

kind: ClassVar[str] = 'assignment'

Explained result. kind belongs to the class contract and is excluded from instance field processing. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: transport leg. Contrast the rule using start, end, minutes and fare. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “ClassVar annotations mark names that are not dataclass fields and therefore do not enter generated instance methods.” Apply this procedure: Inspect fields() and the generated signature to confirm the boundary. The expected mechanism is: kind belongs to the class contract and is excluded from instance field processing. For the transport leg, add one near-miss that exposes forgetting ClassVar and accidentally exposing a shared constant as constructor data. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: project task. Stress-test the rule using owner, priority, state and dependencies. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “ClassVar annotations mark names that are not dataclass fields and therefore do not enter generated instance methods.” Apply this procedure: Inspect fields() and the generated signature to confirm the boundary. The expected mechanism is: kind belongs to the class contract and is excluded from instance field processing. For the project task, add one near-miss that exposes forgetting ClassVar and accidentally exposing a shared constant as constructor data. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: assignment record. Explain the rule using subject, due date, status and an optional note. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “ClassVar annotations mark names that are not dataclass fields and therefore do not enter generated instance methods.” Apply this procedure: Inspect fields() and the generated signature to confirm the boundary. The expected mechanism is: kind belongs to the class contract and is excluded from instance field processing. For the assignment record, add one near-miss that exposes forgetting ClassVar and accidentally exposing a shared constant as constructor data. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: library book. Transfer the rule using title, call number, loan state and borrower. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “ClassVar annotations mark names that are not dataclass fields and therefore do not enter generated instance methods.” Apply this procedure: Inspect fields() and the generated signature to confirm the boundary. The expected mechanism is: kind belongs to the class contract and is excluded from instance field processing. For the library book, add one near-miss that exposes forgetting ClassVar and accidentally exposing a shared constant as constructor data. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Diagnostic route

  • Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
  • Boundary check: create the smallest input that triggers forgetting ClassVar and accidentally exposing a shared constant as constructor data.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Inspect fields() and the generated signature to confirm the boundary.” and record the first changed observation.
  • Transfer check: repeat the rule in a second context and identify what remains invariant.

A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.

Practice with an explained answer

Question. Build a tiny assignment record with subject, due date, status and an optional note. Include one ordinary case, one boundary and one deliberate failure caused by forgetting ClassVar and accidentally exposing a shared constant as constructor data. Predict each result before using a tool, then report the first point where observation differs from prediction.

Answer guide. A strong response starts with the rule: ClassVar annotations mark names that are not dataclass fields and therefore do not enter generated instance methods. It shows a trace, not only a final value. The ordinary case should demonstrate “kind belongs to the class contract and is excluded from instance field processing.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Inspect fields() and the generated signature to confirm the boundary. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.

Previous chapter . Contents . Next chapter

CHAPTER 13 OF 20 . Debug and verify

13. Inheritance and field combination

Back to contents

Dataclass inheritance combines base fields in reverse MRO order, then adds or overrides derived fields. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.

The high-value mistake in this chapter is reading only the child class and missing inherited constructor order or defaults. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Write the complete effective field list before instantiating the subclass.

Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.

Core worked example

@dataclass
class Base: x: float = 1
@dataclass
class Child(Base): y: int = 0

Explained result. Child has the effective field order x then y, with the child able to override compatible definitions. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: assignment record. Stress-test the rule using subject, due date, status and an optional note. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “Dataclass inheritance combines base fields in reverse MRO order, then adds or overrides derived fields.” Apply this procedure: Write the complete effective field list before instantiating the subclass. The expected mechanism is: Child has the effective field order x then y, with the child able to override compatible definitions. For the assignment record, add one near-miss that exposes reading only the child class and missing inherited constructor order or defaults. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: library book. Explain the rule using title, call number, loan state and borrower. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “Dataclass inheritance combines base fields in reverse MRO order, then adds or overrides derived fields.” Apply this procedure: Write the complete effective field list before instantiating the subclass. The expected mechanism is: Child has the effective field order x then y, with the child able to override compatible definitions. For the library book, add one near-miss that exposes reading only the child class and missing inherited constructor order or defaults. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: CCA registration. Transfer the rule using activity, weekday, capacity and participant list. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “Dataclass inheritance combines base fields in reverse MRO order, then adds or overrides derived fields.” Apply this procedure: Write the complete effective field list before instantiating the subclass. The expected mechanism is: Child has the effective field order x then y, with the child able to override compatible definitions. For the CCA registration, add one near-miss that exposes reading only the child class and missing inherited constructor order or defaults. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: science reading. Predict the rule using quantity, unit, uncertainty and observation. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “Dataclass inheritance combines base fields in reverse MRO order, then adds or overrides derived fields.” Apply this procedure: Write the complete effective field list before instantiating the subclass. The expected mechanism is: Child has the effective field order x then y, with the child able to override compatible definitions. For the science reading, add one near-miss that exposes reading only the child class and missing inherited constructor order or defaults. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Diagnostic route

  • Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
  • Boundary check: create the smallest input that triggers reading only the child class and missing inherited constructor order or defaults.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Write the complete effective field list before instantiating the subclass.” and record the first changed observation.
  • Transfer check: repeat the rule in a second context and identify what remains invariant.

A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.

Practice with an explained answer

Question. Build a tiny library book with title, call number, loan state and borrower. Include one ordinary case, one boundary and one deliberate failure caused by reading only the child class and missing inherited constructor order or defaults. Predict each result before using a tool, then report the first point where observation differs from prediction.

Answer guide. A strong response starts with the rule: Dataclass inheritance combines base fields in reverse MRO order, then adds or overrides derived fields. It shows a trace, not only a final value. The ordinary case should demonstrate “Child has the effective field order x then y, with the child able to override compatible definitions.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Write the complete effective field list before instantiating the subclass. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.

Previous chapter . Contents . Next chapter

CHAPTER 14 OF 20 . Debug and verify

14. Keyword-only fields

Back to contents

kw_only=True or KW_ONLY can require explicit names, protecting call sites from ambiguous positional construction. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.

The high-value mistake in this chapter is adding positional fields later and shifting every downstream argument. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Use keyword-only fields for configuration-like options and verify __match_args__ implications.

Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.

Core worked example

@dataclass(kw_only=True)
class Window:
    width: int
    height: int

Explained result. Window(width=4,height=3) is clear; positional construction is rejected. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: CCA registration. Explain the rule using activity, weekday, capacity and participant list. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “kw_only=True or KW_ONLY can require explicit names, protecting call sites from ambiguous positional construction.” Apply this procedure: Use keyword-only fields for configuration-like options and verify __match_args__ implications. The expected mechanism is: Window(width=4,height=3) is clear; positional construction is rejected. For the CCA registration, add one near-miss that exposes adding positional fields later and shifting every downstream argument. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: science reading. Transfer the rule using quantity, unit, uncertainty and observation. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “kw_only=True or KW_ONLY can require explicit names, protecting call sites from ambiguous positional construction.” Apply this procedure: Use keyword-only fields for configuration-like options and verify __match_args__ implications. The expected mechanism is: Window(width=4,height=3) is clear; positional construction is rejected. For the science reading, add one near-miss that exposes adding positional fields later and shifting every downstream argument. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: revision card. Predict the rule using topic, confidence, evidence and next review date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “kw_only=True or KW_ONLY can require explicit names, protecting call sites from ambiguous positional construction.” Apply this procedure: Use keyword-only fields for configuration-like options and verify __match_args__ implications. The expected mechanism is: Window(width=4,height=3) is clear; positional construction is rejected. For the revision card, add one near-miss that exposes adding positional fields later and shifting every downstream argument. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: budget item. Contrast the rule using label, unit cost, quantity and category. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “kw_only=True or KW_ONLY can require explicit names, protecting call sites from ambiguous positional construction.” Apply this procedure: Use keyword-only fields for configuration-like options and verify __match_args__ implications. The expected mechanism is: Window(width=4,height=3) is clear; positional construction is rejected. For the budget item, add one near-miss that exposes adding positional fields later and shifting every downstream argument. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Diagnostic route

  • Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
  • Boundary check: create the smallest input that triggers adding positional fields later and shifting every downstream argument.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Use keyword-only fields for configuration-like options and verify __match_args__ implications.” and record the first changed observation.
  • Transfer check: repeat the rule in a second context and identify what remains invariant.

A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.

Practice with an explained answer

Question. Build a tiny CCA registration with activity, weekday, capacity and participant list. Include one ordinary case, one boundary and one deliberate failure caused by adding positional fields later and shifting every downstream argument. Predict each result before using a tool, then report the first point where observation differs from prediction.

Answer guide. A strong response starts with the rule: kw_only=True or KW_ONLY can require explicit names, protecting call sites from ambiguous positional construction. It shows a trace, not only a final value. The ordinary case should demonstrate “Window(width=4,height=3) is clear; positional construction is rejected.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Use keyword-only fields for configuration-like options and verify __match_args__ implications. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.

Previous chapter . Contents . Next chapter

CHAPTER 15 OF 20 . Debug and verify

15. slots and weak references

Back to contents

slots=True returns a class with generated slots, while weakref_slot requires slots and adds support for weak references. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.

The high-value mistake in this chapter is choosing slots from a performance slogan without measuring or checking inheritance. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Measure memory and behaviour in the real workload, and test subclasses and serialization.

Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.

Core worked example

@dataclass(slots=True)
class Reading:
    page: int

Explained result. Instances do not receive a normal __dict__ merely for undeclared attributes. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: revision card. Transfer the rule using topic, confidence, evidence and next review date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “slots=True returns a class with generated slots, while weakref_slot requires slots and adds support for weak references.” Apply this procedure: Measure memory and behaviour in the real workload, and test subclasses and serialization. The expected mechanism is: Instances do not receive a normal __dict__ merely for undeclared attributes. For the revision card, add one near-miss that exposes choosing slots from a performance slogan without measuring or checking inheritance. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: budget item. Predict the rule using label, unit cost, quantity and category. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “slots=True returns a class with generated slots, while weakref_slot requires slots and adds support for weak references.” Apply this procedure: Measure memory and behaviour in the real workload, and test subclasses and serialization. The expected mechanism is: Instances do not receive a normal __dict__ merely for undeclared attributes. For the budget item, add one near-miss that exposes choosing slots from a performance slogan without measuring or checking inheritance. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: transport leg. Contrast the rule using start, end, minutes and fare. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “slots=True returns a class with generated slots, while weakref_slot requires slots and adds support for weak references.” Apply this procedure: Measure memory and behaviour in the real workload, and test subclasses and serialization. The expected mechanism is: Instances do not receive a normal __dict__ merely for undeclared attributes. For the transport leg, add one near-miss that exposes choosing slots from a performance slogan without measuring or checking inheritance. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: project task. Stress-test the rule using owner, priority, state and dependencies. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “slots=True returns a class with generated slots, while weakref_slot requires slots and adds support for weak references.” Apply this procedure: Measure memory and behaviour in the real workload, and test subclasses and serialization. The expected mechanism is: Instances do not receive a normal __dict__ merely for undeclared attributes. For the project task, add one near-miss that exposes choosing slots from a performance slogan without measuring or checking inheritance. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Diagnostic route

  • Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
  • Boundary check: create the smallest input that triggers choosing slots from a performance slogan without measuring or checking inheritance.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Measure memory and behaviour in the real workload, and test subclasses and serialization.” and record the first changed observation.
  • Transfer check: repeat the rule in a second context and identify what remains invariant.

A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.

Practice with an explained answer

Question. Build a tiny science reading with quantity, unit, uncertainty and observation. Include one ordinary case, one boundary and one deliberate failure caused by choosing slots from a performance slogan without measuring or checking inheritance. Predict each result before using a tool, then report the first point where observation differs from prediction.

Answer guide. A strong response starts with the rule: slots=True returns a class with generated slots, while weakref_slot requires slots and adds support for weak references. It shows a trace, not only a final value. The ordinary case should demonstrate “Instances do not receive a normal __dict__ merely for undeclared attributes.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Measure memory and behaviour in the real workload, and test subclasses and serialization. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.

Previous chapter . Contents . Next chapter

CHAPTER 16 OF 20 . Debug and verify

16. asdict and astuple copy deeply

Back to contents

asdict and astuple recurse through nested dataclasses and deep-copy other contained objects. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.

The high-value mistake in this chapter is calling asdict a free shallow view and being surprised by allocation or identity changes. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Choose the documented conversion or a fields()-based shallow mapping deliberately.

Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.

Core worked example

payload = asdict(record)

Explained result. Nested dataclasses become nested dictionaries, and the conversion is not a live view of the object. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: transport leg. Predict the rule using start, end, minutes and fare. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “asdict and astuple recurse through nested dataclasses and deep-copy other contained objects.” Apply this procedure: Choose the documented conversion or a fields()-based shallow mapping deliberately. The expected mechanism is: Nested dataclasses become nested dictionaries, and the conversion is not a live view of the object. For the transport leg, add one near-miss that exposes calling asdict a free shallow view and being surprised by allocation or identity changes. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: project task. Contrast the rule using owner, priority, state and dependencies. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “asdict and astuple recurse through nested dataclasses and deep-copy other contained objects.” Apply this procedure: Choose the documented conversion or a fields()-based shallow mapping deliberately. The expected mechanism is: Nested dataclasses become nested dictionaries, and the conversion is not a live view of the object. For the project task, add one near-miss that exposes calling asdict a free shallow view and being surprised by allocation or identity changes. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: assignment record. Stress-test the rule using subject, due date, status and an optional note. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “asdict and astuple recurse through nested dataclasses and deep-copy other contained objects.” Apply this procedure: Choose the documented conversion or a fields()-based shallow mapping deliberately. The expected mechanism is: Nested dataclasses become nested dictionaries, and the conversion is not a live view of the object. For the assignment record, add one near-miss that exposes calling asdict a free shallow view and being surprised by allocation or identity changes. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: library book. Explain the rule using title, call number, loan state and borrower. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “asdict and astuple recurse through nested dataclasses and deep-copy other contained objects.” Apply this procedure: Choose the documented conversion or a fields()-based shallow mapping deliberately. The expected mechanism is: Nested dataclasses become nested dictionaries, and the conversion is not a live view of the object. For the library book, add one near-miss that exposes calling asdict a free shallow view and being surprised by allocation or identity changes. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Diagnostic route

  • Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
  • Boundary check: create the smallest input that triggers calling asdict a free shallow view and being surprised by allocation or identity changes.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Choose the documented conversion or a fields()-based shallow mapping deliberately.” and record the first changed observation.
  • Transfer check: repeat the rule in a second context and identify what remains invariant.

A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.

Practice with an explained answer

Question. Build a tiny revision card with topic, confidence, evidence and next review date. Include one ordinary case, one boundary and one deliberate failure caused by calling asdict a free shallow view and being surprised by allocation or identity changes. Predict each result before using a tool, then report the first point where observation differs from prediction.

Answer guide. A strong response starts with the rule: asdict and astuple recurse through nested dataclasses and deep-copy other contained objects. It shows a trace, not only a final value. The ordinary case should demonstrate “Nested dataclasses become nested dictionaries, and the conversion is not a live view of the object.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Choose the documented conversion or a fields()-based shallow mapping deliberately. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.

Previous chapter . Contents . Next chapter

CHAPTER 17 OF 20 . Transfer with judgment

17. replace constructs and validates again

Back to contents

replace creates a new same-type object through __init__, so __post_init__ runs and init-only requirements still matter. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.

The high-value mistake in this chapter is treating replace as a raw memory copy that bypasses validation. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Predict derived fields and validation before using replace in an update workflow.

Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.

Core worked example

revised = replace(original, score=82)

Explained result. A new object is constructed with score changed, and post-init rules are re-applied. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: assignment record. Contrast the rule using subject, due date, status and an optional note. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “replace creates a new same-type object through __init__, so __post_init__ runs and init-only requirements still matter.” Apply this procedure: Predict derived fields and validation before using replace in an update workflow. The expected mechanism is: A new object is constructed with score changed, and post-init rules are re-applied. For the assignment record, add one near-miss that exposes treating replace as a raw memory copy that bypasses validation. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: library book. Stress-test the rule using title, call number, loan state and borrower. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “replace creates a new same-type object through __init__, so __post_init__ runs and init-only requirements still matter.” Apply this procedure: Predict derived fields and validation before using replace in an update workflow. The expected mechanism is: A new object is constructed with score changed, and post-init rules are re-applied. For the library book, add one near-miss that exposes treating replace as a raw memory copy that bypasses validation. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: CCA registration. Explain the rule using activity, weekday, capacity and participant list. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “replace creates a new same-type object through __init__, so __post_init__ runs and init-only requirements still matter.” Apply this procedure: Predict derived fields and validation before using replace in an update workflow. The expected mechanism is: A new object is constructed with score changed, and post-init rules are re-applied. For the CCA registration, add one near-miss that exposes treating replace as a raw memory copy that bypasses validation. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: science reading. Transfer the rule using quantity, unit, uncertainty and observation. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “replace creates a new same-type object through __init__, so __post_init__ runs and init-only requirements still matter.” Apply this procedure: Predict derived fields and validation before using replace in an update workflow. The expected mechanism is: A new object is constructed with score changed, and post-init rules are re-applied. For the science reading, add one near-miss that exposes treating replace as a raw memory copy that bypasses validation. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Diagnostic route

  • Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
  • Boundary check: create the smallest input that triggers treating replace as a raw memory copy that bypasses validation.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Predict derived fields and validation before using replace in an update workflow.” and record the first changed observation.
  • Transfer check: repeat the rule in a second context and identify what remains invariant.

A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.

Practice with an explained answer

Question. Build a tiny budget item with label, unit cost, quantity and category. Include one ordinary case, one boundary and one deliberate failure caused by treating replace as a raw memory copy that bypasses validation. Predict each result before using a tool, then report the first point where observation differs from prediction.

Answer guide. A strong response starts with the rule: replace creates a new same-type object through __init__, so __post_init__ runs and init-only requirements still matter. It shows a trace, not only a final value. The ordinary case should demonstrate “A new object is constructed with score changed, and post-init rules are re-applied.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Predict derived fields and validation before using replace in an update workflow. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.

Previous chapter . Contents . Next chapter

CHAPTER 18 OF 20 . Transfer with judgment

18. fields and is_dataclass for introspection

Back to contents

fields returns documented Field objects for real dataclass fields, while is_dataclass recognises both decorated classes and instances. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.

The high-value mistake in this chapter is probing private attributes or __slots__ to discover schema. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Use public introspection and separately distinguish a class from an instance when needed.

Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.

Core worked example

names = [f.name for f in fields(Quiz)]

Explained result. The list follows the effective dataclass field order and excludes ClassVar and InitVar pseudo-fields. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: CCA registration. Stress-test the rule using activity, weekday, capacity and participant list. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “fields returns documented Field objects for real dataclass fields, while is_dataclass recognises both decorated classes and instances.” Apply this procedure: Use public introspection and separately distinguish a class from an instance when needed. The expected mechanism is: The list follows the effective dataclass field order and excludes ClassVar and InitVar pseudo-fields. For the CCA registration, add one near-miss that exposes probing private attributes or __slots__ to discover schema. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: science reading. Explain the rule using quantity, unit, uncertainty and observation. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “fields returns documented Field objects for real dataclass fields, while is_dataclass recognises both decorated classes and instances.” Apply this procedure: Use public introspection and separately distinguish a class from an instance when needed. The expected mechanism is: The list follows the effective dataclass field order and excludes ClassVar and InitVar pseudo-fields. For the science reading, add one near-miss that exposes probing private attributes or __slots__ to discover schema. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: revision card. Transfer the rule using topic, confidence, evidence and next review date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “fields returns documented Field objects for real dataclass fields, while is_dataclass recognises both decorated classes and instances.” Apply this procedure: Use public introspection and separately distinguish a class from an instance when needed. The expected mechanism is: The list follows the effective dataclass field order and excludes ClassVar and InitVar pseudo-fields. For the revision card, add one near-miss that exposes probing private attributes or __slots__ to discover schema. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: budget item. Predict the rule using label, unit cost, quantity and category. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “fields returns documented Field objects for real dataclass fields, while is_dataclass recognises both decorated classes and instances.” Apply this procedure: Use public introspection and separately distinguish a class from an instance when needed. The expected mechanism is: The list follows the effective dataclass field order and excludes ClassVar and InitVar pseudo-fields. For the budget item, add one near-miss that exposes probing private attributes or __slots__ to discover schema. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Diagnostic route

  • Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
  • Boundary check: create the smallest input that triggers probing private attributes or __slots__ to discover schema.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Use public introspection and separately distinguish a class from an instance when needed.” and record the first changed observation.
  • Transfer check: repeat the rule in a second context and identify what remains invariant.

A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.

Practice with an explained answer

Question. Build a tiny transport leg with start, end, minutes and fare. Include one ordinary case, one boundary and one deliberate failure caused by probing private attributes or __slots__ to discover schema. Predict each result before using a tool, then report the first point where observation differs from prediction.

Answer guide. A strong response starts with the rule: fields returns documented Field objects for real dataclass fields, while is_dataclass recognises both decorated classes and instances. It shows a trace, not only a final value. The ordinary case should demonstrate “The list follows the effective dataclass field order and excludes ClassVar and InitVar pseudo-fields.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Use public introspection and separately distinguish a class from an instance when needed. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.

Previous chapter . Contents . Next chapter

CHAPTER 19 OF 20 . Transfer with judgment

19. Pattern matching and __match_args__

Back to contents

Dataclasses can generate __match_args__ from non-keyword-only constructor fields, influencing positional class patterns. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.

The high-value mistake in this chapter is publishing positional pattern semantics accidentally and later reordering fields. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Prefer named patterns for durable code and set match_args deliberately.

Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.

Core worked example

match point:
    case Point(x=0, y=y): ...

Explained result. The named pattern states the field contract without depending on positional field order. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: revision card. Explain the rule using topic, confidence, evidence and next review date. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “Dataclasses can generate __match_args__ from non-keyword-only constructor fields, influencing positional class patterns.” Apply this procedure: Prefer named patterns for durable code and set match_args deliberately. The expected mechanism is: The named pattern states the field contract without depending on positional field order. For the revision card, add one near-miss that exposes publishing positional pattern semantics accidentally and later reordering fields. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: budget item. Transfer the rule using label, unit cost, quantity and category. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “Dataclasses can generate __match_args__ from non-keyword-only constructor fields, influencing positional class patterns.” Apply this procedure: Prefer named patterns for durable code and set match_args deliberately. The expected mechanism is: The named pattern states the field contract without depending on positional field order. For the budget item, add one near-miss that exposes publishing positional pattern semantics accidentally and later reordering fields. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: transport leg. Predict the rule using start, end, minutes and fare. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “Dataclasses can generate __match_args__ from non-keyword-only constructor fields, influencing positional class patterns.” Apply this procedure: Prefer named patterns for durable code and set match_args deliberately. The expected mechanism is: The named pattern states the field contract without depending on positional field order. For the transport leg, add one near-miss that exposes publishing positional pattern semantics accidentally and later reordering fields. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: project task. Contrast the rule using owner, priority, state and dependencies. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “Dataclasses can generate __match_args__ from non-keyword-only constructor fields, influencing positional class patterns.” Apply this procedure: Prefer named patterns for durable code and set match_args deliberately. The expected mechanism is: The named pattern states the field contract without depending on positional field order. For the project task, add one near-miss that exposes publishing positional pattern semantics accidentally and later reordering fields. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Diagnostic route

  • Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
  • Boundary check: create the smallest input that triggers publishing positional pattern semantics accidentally and later reordering fields.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Prefer named patterns for durable code and set match_args deliberately.” and record the first changed observation.
  • Transfer check: repeat the rule in a second context and identify what remains invariant.

A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.

Practice with an explained answer

Question. Build a tiny project task with owner, priority, state and dependencies. Include one ordinary case, one boundary and one deliberate failure caused by publishing positional pattern semantics accidentally and later reordering fields. Predict each result before using a tool, then report the first point where observation differs from prediction.

Answer guide. A strong response starts with the rule: Dataclasses can generate __match_args__ from non-keyword-only constructor fields, influencing positional class patterns. It shows a trace, not only a final value. The ordinary case should demonstrate “The named pattern states the field contract without depending on positional field order.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Prefer named patterns for durable code and set match_args deliberately. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.

Previous chapter . Contents . Next chapter

CHAPTER 20 OF 20 . Transfer with judgment

20. Choosing a dataclass with judgment

Back to contents

A dataclass suits record-like objects with field-driven behaviour; a plain class suits custom invariants and lifecycle, while tuples or mappings suit other contracts. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.

The high-value mistake in this chapter is using @dataclass merely to avoid writing code even when the generated semantics are wrong. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. List the required construction, equality, mutability, representation and inheritance policies before selecting the form.

Use a two-column trace during a short Punggol home session. On the left, write the predicted state before the interpreter, browser, database or Git command runs. On the right, record the exact observation. Underneath, explain the earliest difference with one causal sentence. That small routine is more diagnostic than copying a finished answer.

Core worked example

# Choose the model before the decorator

Explained result. The best design is the one whose default behaviour matches the domain and remains explainable to the next reader. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: transport leg. Transfer the rule using start, end, minutes and fare. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “A dataclass suits record-like objects with field-driven behaviour; a plain class suits custom invariants and lifecycle, while tuples or mappings suit other contracts.” Apply this procedure: List the required construction, equality, mutability, representation and inheritance policies before selecting the form. The expected mechanism is: The best design is the one whose default behaviour matches the domain and remains explainable to the next reader. For the transport leg, add one near-miss that exposes using @dataclass merely to avoid writing code even when the generated semantics are wrong. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: project task. Predict the rule using owner, priority, state and dependencies. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “A dataclass suits record-like objects with field-driven behaviour; a plain class suits custom invariants and lifecycle, while tuples or mappings suit other contracts.” Apply this procedure: List the required construction, equality, mutability, representation and inheritance policies before selecting the form. The expected mechanism is: The best design is the one whose default behaviour matches the domain and remains explainable to the next reader. For the project task, add one near-miss that exposes using @dataclass merely to avoid writing code even when the generated semantics are wrong. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: assignment record. Contrast the rule using subject, due date, status and an optional note. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “A dataclass suits record-like objects with field-driven behaviour; a plain class suits custom invariants and lifecycle, while tuples or mappings suit other contracts.” Apply this procedure: List the required construction, equality, mutability, representation and inheritance policies before selecting the form. The expected mechanism is: The best design is the one whose default behaviour matches the domain and remains explainable to the next reader. For the assignment record, add one near-miss that exposes using @dataclass merely to avoid writing code even when the generated semantics are wrong. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: library book. Stress-test the rule using title, call number, loan state and borrower. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “A dataclass suits record-like objects with field-driven behaviour; a plain class suits custom invariants and lifecycle, while tuples or mappings suit other contracts.” Apply this procedure: List the required construction, equality, mutability, representation and inheritance policies before selecting the form. The expected mechanism is: The best design is the one whose default behaviour matches the domain and remains explainable to the next reader. For the library book, add one near-miss that exposes using @dataclass merely to avoid writing code even when the generated semantics are wrong. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Diagnostic route

  • Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
  • Boundary check: create the smallest input that triggers using @dataclass merely to avoid writing code even when the generated semantics are wrong.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “List the required construction, equality, mutability, representation and inheritance policies before selecting the form.” and record the first changed observation.
  • Transfer check: repeat the rule in a second context and identify what remains invariant.

A parent does not need to know the final syntax. Useful prompts are: “What did you expect?”, “Which state changed first?”, “What evidence would change your mind?”, and “Can you make the example smaller?” These questions return responsibility to the learner while keeping the session calm and concrete.

Practice with an explained answer

Question. Build a tiny assignment record with subject, due date, status and an optional note. Include one ordinary case, one boundary and one deliberate failure caused by using @dataclass merely to avoid writing code even when the generated semantics are wrong. Predict each result before using a tool, then report the first point where observation differs from prediction.

Answer guide. A strong response starts with the rule: A dataclass suits record-like objects with field-driven behaviour; a plain class suits custom invariants and lifecycle, while tuples or mappings suit other contracts. It shows a trace, not only a final value. The ordinary case should demonstrate “The best design is the one whose default behaviour matches the domain and remains explainable to the next reader.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: List the required construction, equality, mutability, representation and inheritance policies before selecting the form. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

Separate mechanism from project policy. The mechanism is the behaviour guaranteed by the current official documentation. The policy is the choice this project makes about validation, ordering, ownership, performance or recovery. Write both statements before generalising. Keep important work backed up and use disposable examples for destructive or stateful experiments.

Previous chapter . Contents . Next chapter

Parent guide: choose the next useful step

Start with evidence, not a label such as careless. Ask for one prediction and one trace. If the first transition is wrong, rebuild the model. If the model is sound but syntax fails, practise reference use. If routine cases are correct but boundaries fail, vary ties, defaults, unsupported inputs, ownership or missing paths. If explanations transfer, move to a small project.

Keep a weekly record with four lines: concept, prediction, observed difference and next test. Stop when fatigue replaces reasoning. A smaller case tomorrow is more useful than another hour of copying tonight.

Seek specialist help when cause and effect remain invisible after examples are reduced, when accessibility or data-loss implications are unclear, or when an important repository, database or application state may be at risk. Good support should make the learner’s reasoning more independent.

Capstone practice with explained routes

1. assignment record: model, boundary and recovery

Create a small assignment record using subject, due date, status and an optional note. Combine “The generated-method mental model” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.

Explained route. Start with: The decorator reads annotated fields and may generate methods on the same class; it does not turn data into a dictionary or perform runtime type validation. Apply: Inspect the generated signature and compare repr and equality on two tiny instances. Verify: Task(‘Read’) accepts name and supplies done=False; the annotation documents intent but does not itself enforce str. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.

2. library book: model, boundary and recovery

Create a small library book using title, call number, loan state and borrower. Combine “default_factory and mutable values” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.

Explained route. Start with: default_factory calls a zero-argument function for each new instance, preventing accidental sharing of mutable defaults. Apply: Create two instances, mutate one collection and prove the other is independent. Verify: Each Plan receives a distinct list, so adding to one plan does not modify another. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.

3. CCA registration: model, boundary and recovery

Create a small CCA registration using activity, weekday, capacity and participant list. Combine “Ordering is tuple-like” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.

Explained route. Start with: order=True generates rich comparisons from participating fields in declaration order, provided equality is enabled. Apply: State the sort key implied by field order, then compare it with an explicit key function. Verify: Results sort by score first and use name only when scores tie. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.

4. science reading: model, boundary and recovery

Create a small science reading using quantity, unit, uncertainty and observation. Combine “__post_init__ and invariants” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.

Explained route. Start with: The generated __init__ calls __post_init__ so related fields can be validated or derived after assignment. Apply: State each invariant, raise a precise exception and test every boundary. Verify: Construction fails at the domain boundary instead of allowing an impossible interval. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.

5. revision card: model, boundary and recovery

Create a small revision card using topic, confidence, evidence and next review date. Combine “Inheritance and field combination” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.

Explained route. Start with: Dataclass inheritance combines base fields in reverse MRO order, then adds or overrides derived fields. Apply: Write the complete effective field list before instantiating the subclass. Verify: Child has the effective field order x then y, with the child able to override compatible definitions. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.

6. budget item: model, boundary and recovery

Create a small budget item using label, unit cost, quantity and category. Combine “asdict and astuple copy deeply” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.

Explained route. Start with: asdict and astuple recurse through nested dataclasses and deep-copy other contained objects. Apply: Choose the documented conversion or a fields()-based shallow mapping deliberately. Verify: Nested dataclasses become nested dictionaries, and the conversion is not a live view of the object. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.

7. transport leg: model, boundary and recovery

Create a small transport leg using start, end, minutes and fare. Combine “Pattern matching and __match_args__” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.

Explained route. Start with: Dataclasses can generate __match_args__ from non-keyword-only constructor fields, influencing positional class patterns. Apply: Prefer named patterns for durable code and set match_args deliberately. Verify: The named pattern states the field contract without depending on positional field order. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.

8. project task: model, boundary and recovery

Create a small project task using owner, priority, state and dependencies. Combine “Field order and constructor order” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.

Explained route. Start with: Field declaration order determines parameter order and participates in generated repr, equality and ordering behaviour. Apply: Prefer clear field order and keyword calls at boundaries; inspect the signature after refactoring. Verify: Point(2, 5) binds x=2 and y=5 because declaration order drives the generated constructor. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.

Frequently asked questions

How long should a practice session be?

Use one complete prediction–observation–explanation cycle while attention remains good. Ten to twenty focused minutes can be enough.

Should every option or function be memorised?

No. Memorise the governing distinctions and practise retrieving the official reference. Understanding means predicting and explaining, not reciting a parameter list.

What if the result is correct but the explanation is weak?

Treat it as partial success. Ask for a trace and change one boundary. A reliable model survives controlled variation.

Is the shortest solution the best?

Not automatically. Prefer the solution whose semantics, failure modes and maintenance cost are easiest to justify for the actual project.

When should official documentation be used?

Use it whenever syntax, supported types, SQL dialect behaviour or Git version details matter. Primary documentation settles the current contract.

How can a parent help without technical expertise?

Ask what was predicted, where the first difference appeared, what evidence matters and which smaller example could isolate it.

How do we test transfer?

Change the context, vocabulary and one boundary. Require the learner to identify the invariant before using a tool.

What should be saved after practice?

Keep the corrected rule, one trace, one boundary case and the next question. Avoid storing pages of unexplained output.

Can these exercises replace backups?

No. Use disposable examples and proper backups. Learning should not endanger schoolwork, repositories or personal data.

What counts as mastery?

The learner can predict, verify, diagnose, recover and justify a choice across more than one context, while knowing when to consult the current reference.

Official and supporting references

Return to contents

Continue from here: Start Here · Tuition · Education · Pathways · Parenting 101 · All Site Routes

eduKate Punggol

Contact

83 Punggol Central, Singapore 828761

edu|Kate Bukit Timah

8 Fourth Avenue, Singapore 268674

By Appointment +65 8823 1234
admin@edukatesg.com

Email Us

When a child finally understands, school becomes less frightening and the future opens wider. Email us for the latest schedules and fees.

← 返回

感谢您的回复。 ✨

了解 eduKate Punggol 的更多信息

立即订阅以继续阅读并访问完整档案。

继续阅读