Small Group Tutorials

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

How to Master Python functools.total_ordering in Punggol Tuition

Student holds a dark notebook with a hand beside the face while seated on a stone bench.

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.

Python functools.total_ordering can derive the missing rich comparison methods when a class supplies __eq__ and at least one ordering method. That convenience is safe only when the underlying comparison defines one coherent order, returns NotImplemented for unsupported operands, respects equality and hashing rules, and survives inheritance, mixed types and boundary cases. Mastery means understanding the generated methods rather than merely adding a decorator. 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 decorator derives missing rich comparisons

Back to contents

A class supplies __eq__ plus one of __lt__, __le__, __gt__ or __ge__; total_ordering synthesises the other ordering 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 assuming the decorator invents the meaning of equality or ordering. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. List the supplied methods, generated methods and domain key before running comparisons.

For the The decorator derives missing rich comparisons chapter on Python functools.total_ordering, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on assuming the decorator invents the meaning of equality or ordering. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from functools import total_ordering
@total_ordering
class Mark:
 def __init__(self,n): self.n=n
 def __eq__(self,o): return isinstance(o,Mark) and self.n==o.n
 def __lt__(self,o):
  if not isinstance(o,Mark): return NotImplemented
  return self.n<o.n
print(Mark(2)<=Mark(3))

Explained result. The result is True; __le__ is derived from the two methods whose meaning the class author supplied. 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: library loans. Predict the rule using ordering due dates while preserving identity and overdue status. 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 class supplies __eq__ plus one of __lt__, __le__, __gt__ or __ge__; total_ordering synthesises the other ordering methods.” Apply this procedure: List the supplied methods, generated methods and domain key before running comparisons. The expected mechanism is: The result is True; __le__ is derived from the two methods whose meaning the class author supplied. For the library loans, add one near-miss that exposes assuming the decorator invents the meaning of equality or ordering. 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: student projects. Contrast the rule using ranking immutable version records without confusing score with identity. 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 class supplies __eq__ plus one of __lt__, __le__, __gt__ or __ge__; total_ordering synthesises the other ordering methods.” Apply this procedure: List the supplied methods, generated methods and domain key before running comparisons. The expected mechanism is: The result is True; __le__ is derived from the two methods whose meaning the class author supplied. For the student projects, add one near-miss that exposes assuming the decorator invents the meaning of equality or ordering. 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 fixtures. Stress-test the rule using sorting scheduled matches with postponed entries. 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 class supplies __eq__ plus one of __lt__, __le__, __gt__ or __ge__; total_ordering synthesises the other ordering methods.” Apply this procedure: List the supplied methods, generated methods and domain key before running comparisons. The expected mechanism is: The result is True; __le__ is derived from the two methods whose meaning the class author supplied. For the CCA fixtures, add one near-miss that exposes assuming the decorator invents the meaning of equality or ordering. 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: home budget. Explain the rule using comparing money values only within a currency. 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 class supplies __eq__ plus one of __lt__, __le__, __gt__ or __ge__; total_ordering synthesises the other ordering methods.” Apply this procedure: List the supplied methods, generated methods and domain key before running comparisons. The expected mechanism is: The result is True; __le__ is derived from the two methods whose meaning the class author supplied. For the home budget, add one near-miss that exposes assuming the decorator invents the meaning of equality or ordering. 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 the decorator invents the meaning of equality or ordering.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “List the supplied methods, generated methods and domain key before running comparisons.” 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 Python functools.total_ordering syntax. For this chapter, useful prompts are: “What did you expect from The decorator derives missing rich comparisons?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing assuming the decorator invents the meaning of equality or ordering be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny data import with rejecting incompatible or incomplete external records. Include one ordinary case, one boundary and one deliberate failure caused by assuming the decorator invents the meaning of equality or ordering. 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 class supplies __eq__ plus one of __lt__, __le__, __gt__ or __ge__; total_ordering synthesises the other ordering methods. It shows a trace, not only a final value. The ordinary case should demonstrate “The result is True; __le__ is derived from the two methods whose meaning the class author supplied.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: List the supplied methods, generated methods and domain key before running comparisons. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For The decorator derives missing rich comparisons, separate the documented Python functools.total_ordering mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.

Previous chapter . Contents . Next chapter

CHAPTER 2 OF 20 . Build the model

2. At least one ordering method is mandatory

Back to contents

Equality alone cannot tell Python whether a different object is lower or higher, so decoration fails without an ordering primitive. 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 believing __eq__ contains enough information to generate a total order. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Remove the ordering method in a disposable class and keep the definition-time exception as evidence.

For the At least one ordering method is mandatory chapter on Python functools.total_ordering, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on believing __eq__ contains enough information to generate a total order. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from functools import total_ordering
try:
 @total_ordering
 class OnlyEqual:
  def __eq__(self,o): return True
except ValueError as e: print(type(e).__name__)

Explained result. The class definition raises ValueError because no ordering operation is available to derive the rest. 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 fixtures. Contrast the rule using sorting scheduled matches with postponed entries. 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 “Equality alone cannot tell Python whether a different object is lower or higher, so decoration fails without an ordering primitive.” Apply this procedure: Remove the ordering method in a disposable class and keep the definition-time exception as evidence. The expected mechanism is: The class definition raises ValueError because no ordering operation is available to derive the rest. For the CCA fixtures, add one near-miss that exposes believing __eq__ contains enough information to generate a total order. 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: home budget. Stress-test the rule using comparing money values only within a currency. 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 “Equality alone cannot tell Python whether a different object is lower or higher, so decoration fails without an ordering primitive.” Apply this procedure: Remove the ordering method in a disposable class and keep the definition-time exception as evidence. The expected mechanism is: The class definition raises ValueError because no ordering operation is available to derive the rest. For the home budget, add one near-miss that exposes believing __eq__ contains enough information to generate a total order. 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 cards. Explain the rule using ordering priorities with explicit tie breakers. 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 “Equality alone cannot tell Python whether a different object is lower or higher, so decoration fails without an ordering primitive.” Apply this procedure: Remove the ordering method in a disposable class and keep the definition-time exception as evidence. The expected mechanism is: The class definition raises ValueError because no ordering operation is available to derive the rest. For the revision cards, add one near-miss that exposes believing __eq__ contains enough information to generate a total order. 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: data import. Transfer the rule using rejecting incompatible or incomplete external records. 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 “Equality alone cannot tell Python whether a different object is lower or higher, so decoration fails without an ordering primitive.” Apply this procedure: Remove the ordering method in a disposable class and keep the definition-time exception as evidence. The expected mechanism is: The class definition raises ValueError because no ordering operation is available to derive the rest. For the data import, add one near-miss that exposes believing __eq__ contains enough information to generate a total order. 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 believing __eq__ contains enough information to generate a total order.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Remove the ordering method in a disposable class and keep the definition-time exception as evidence.” 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 Python functools.total_ordering syntax. For this chapter, useful prompts are: “What did you expect from At least one ordering method is mandatory?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing believing __eq__ contains enough information to generate a total order be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny test laboratory with checking reflexivity, antisymmetry, transitivity and totality. Include one ordinary case, one boundary and one deliberate failure caused by believing __eq__ contains enough information to generate a total order. 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: Equality alone cannot tell Python whether a different object is lower or higher, so decoration fails without an ordering primitive. It shows a trace, not only a final value. The ordinary case should demonstrate “The class definition raises ValueError because no ordering operation is available to derive the rest.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Remove the ordering method in a disposable class and keep the definition-time exception as evidence. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For At least one ordering method is mandatory, separate the documented Python functools.total_ordering mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.

Previous chapter . Contents . Next chapter

CHAPTER 3 OF 20 . Build the model

3. One canonical comparison key keeps methods coherent

Back to contents

Equality and ordering should normally compare the same immutable semantic key, including every required tie breaker. 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 field for equality and a different field for ordering. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Write the key once and inspect objects that tie on its first component.

For the One canonical comparison key keeps methods coherent chapter on Python functools.total_ordering, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on using one field for equality and a different field for ordering. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

print((2,'b')>(2,'a'))

Explained result. Tuple comparison uses the second component to break the tie; the domain key should make that rule explicit. 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 cards. Stress-test the rule using ordering priorities with explicit tie breakers. 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 “Equality and ordering should normally compare the same immutable semantic key, including every required tie breaker.” Apply this procedure: Write the key once and inspect objects that tie on its first component. The expected mechanism is: Tuple comparison uses the second component to break the tie; the domain key should make that rule explicit. For the revision cards, add one near-miss that exposes using one field for equality and a different field for ordering. 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: data import. Explain the rule using rejecting incompatible or incomplete external records. 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 “Equality and ordering should normally compare the same immutable semantic key, including every required tie breaker.” Apply this procedure: Write the key once and inspect objects that tie on its first component. The expected mechanism is: Tuple comparison uses the second component to break the tie; the domain key should make that rule explicit. For the data import, add one near-miss that exposes using one field for equality and a different field for ordering. 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: test laboratory. Transfer the rule using checking reflexivity, antisymmetry, transitivity and totality. 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 “Equality and ordering should normally compare the same immutable semantic key, including every required tie breaker.” Apply this procedure: Write the key once and inspect objects that tie on its first component. The expected mechanism is: Tuple comparison uses the second component to break the tie; the domain key should make that rule explicit. For the test laboratory, add one near-miss that exposes using one field for equality and a different field for ordering. 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: design review. Predict the rule using comparing total_ordering, manual methods, dataclasses and key functions. 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 “Equality and ordering should normally compare the same immutable semantic key, including every required tie breaker.” Apply this procedure: Write the key once and inspect objects that tie on its first component. The expected mechanism is: Tuple comparison uses the second component to break the tie; the domain key should make that rule explicit. For the design review, add one near-miss that exposes using one field for equality and a different field for ordering. 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 field for equality and a different field for ordering.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Write the key once and inspect objects that tie on its first component.” 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 Python functools.total_ordering syntax. For this chapter, useful prompts are: “What did you expect from One canonical comparison key keeps methods coherent?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing using one field for equality and a different field for ordering be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny design review with comparing total_ordering, manual methods, dataclasses and key functions. Include one ordinary case, one boundary and one deliberate failure caused by using one field for equality and a different field for ordering. 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: Equality and ordering should normally compare the same immutable semantic key, including every required tie breaker. It shows a trace, not only a final value. The ordinary case should demonstrate “Tuple comparison uses the second component to break the tie; the domain key should make that rule explicit.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Write the key once and inspect objects that tie on its first component. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For One canonical comparison key keeps methods coherent, separate the documented Python functools.total_ordering mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.

Previous chapter . Contents . Next chapter

CHAPTER 4 OF 20 . Build the model

4. Return NotImplemented for unsupported operands

Back to contents

NotImplemented lets Python try the reflected operation or raise TypeError instead of receiving a misleading boolean. 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 returning False for every foreign type and silently claiming a meaningful order. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Compare with one compatible object and one foreign value while tracing the protocol.

For the Return NotImplemented for unsupported operands chapter on Python functools.total_ordering, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on returning False for every foreign type and silently claiming a meaningful order. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

m=Mark(2)
try: print(m<'2')
except TypeError as e: print(type(e).__name__)

Explained result. The unsupported mixed comparison becomes TypeError rather than pretending the Mark is not lower. 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: test laboratory. Explain the rule using checking reflexivity, antisymmetry, transitivity and totality. 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 “NotImplemented lets Python try the reflected operation or raise TypeError instead of receiving a misleading boolean.” Apply this procedure: Compare with one compatible object and one foreign value while tracing the protocol. The expected mechanism is: The unsupported mixed comparison becomes TypeError rather than pretending the Mark is not lower. For the test laboratory, add one near-miss that exposes returning False for every foreign type and silently claiming a meaningful order. 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: design review. Transfer the rule using comparing total_ordering, manual methods, dataclasses and key functions. 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 “NotImplemented lets Python try the reflected operation or raise TypeError instead of receiving a misleading boolean.” Apply this procedure: Compare with one compatible object and one foreign value while tracing the protocol. The expected mechanism is: The unsupported mixed comparison becomes TypeError rather than pretending the Mark is not lower. For the design review, add one near-miss that exposes returning False for every foreign type and silently claiming a meaningful order. 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: library loans. Predict the rule using ordering due dates while preserving identity and overdue status. 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 “NotImplemented lets Python try the reflected operation or raise TypeError instead of receiving a misleading boolean.” Apply this procedure: Compare with one compatible object and one foreign value while tracing the protocol. The expected mechanism is: The unsupported mixed comparison becomes TypeError rather than pretending the Mark is not lower. For the library loans, add one near-miss that exposes returning False for every foreign type and silently claiming a meaningful order. 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: student projects. Contrast the rule using ranking immutable version records without confusing score with identity. 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 “NotImplemented lets Python try the reflected operation or raise TypeError instead of receiving a misleading boolean.” Apply this procedure: Compare with one compatible object and one foreign value while tracing the protocol. The expected mechanism is: The unsupported mixed comparison becomes TypeError rather than pretending the Mark is not lower. For the student projects, add one near-miss that exposes returning False for every foreign type and silently claiming a meaningful order. 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 returning False for every foreign type and silently claiming a meaningful order.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Compare with one compatible object and one foreign value while tracing the protocol.” 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 Python functools.total_ordering syntax. For this chapter, useful prompts are: “What did you expect from Return NotImplemented for unsupported operands?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing returning False for every foreign type and silently claiming a meaningful order be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny library loans with ordering due dates while preserving identity and overdue status. Include one ordinary case, one boundary and one deliberate failure caused by returning False for every foreign type and silently claiming a meaningful order. 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: NotImplemented lets Python try the reflected operation or raise TypeError instead of receiving a misleading boolean. It shows a trace, not only a final value. The ordinary case should demonstrate “The unsupported mixed comparison becomes TypeError rather than pretending the Mark is not lower.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Compare with one compatible object and one foreign value while tracing the protocol. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Return NotImplemented for unsupported operands, separate the documented Python functools.total_ordering mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.

Previous chapter . Contents . Next chapter

CHAPTER 5 OF 20 . Use the core tools

5. NotImplemented is not NotImplementedError

Back to contents

NotImplemented is a return sentinel for binary protocol negotiation; NotImplementedError is an exception for an unimplemented API. 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 raising NotImplemented or returning NotImplementedError. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Write the exact return statement and inspect the sentinel type.

For the NotImplemented is not NotImplementedError chapter on Python functools.total_ordering, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on raising NotImplemented or returning NotImplementedError. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

print(type(NotImplemented).__name__)

Explained result. The sentinel has type NotImplementedType and is returned, not raised. 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: library loans. Transfer the rule using ordering due dates while preserving identity and overdue status. 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 “NotImplemented is a return sentinel for binary protocol negotiation; NotImplementedError is an exception for an unimplemented API.” Apply this procedure: Write the exact return statement and inspect the sentinel type. The expected mechanism is: The sentinel has type NotImplementedType and is returned, not raised. For the library loans, add one near-miss that exposes raising NotImplemented or returning NotImplementedError. 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: student projects. Predict the rule using ranking immutable version records without confusing score with identity. 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 “NotImplemented is a return sentinel for binary protocol negotiation; NotImplementedError is an exception for an unimplemented API.” Apply this procedure: Write the exact return statement and inspect the sentinel type. The expected mechanism is: The sentinel has type NotImplementedType and is returned, not raised. For the student projects, add one near-miss that exposes raising NotImplemented or returning NotImplementedError. 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 fixtures. Contrast the rule using sorting scheduled matches with postponed entries. 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 “NotImplemented is a return sentinel for binary protocol negotiation; NotImplementedError is an exception for an unimplemented API.” Apply this procedure: Write the exact return statement and inspect the sentinel type. The expected mechanism is: The sentinel has type NotImplementedType and is returned, not raised. For the CCA fixtures, add one near-miss that exposes raising NotImplemented or returning NotImplementedError. 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: home budget. Stress-test the rule using comparing money values only within a currency. 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 “NotImplemented is a return sentinel for binary protocol negotiation; NotImplementedError is an exception for an unimplemented API.” Apply this procedure: Write the exact return statement and inspect the sentinel type. The expected mechanism is: The sentinel has type NotImplementedType and is returned, not raised. For the home budget, add one near-miss that exposes raising NotImplemented or returning NotImplementedError. 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 raising NotImplemented or returning NotImplementedError.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Write the exact return statement and inspect the sentinel type.” 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 Python functools.total_ordering syntax. For this chapter, useful prompts are: “What did you expect from NotImplemented is not NotImplementedError?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing raising NotImplemented or returning NotImplementedError be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny student projects with ranking immutable version records without confusing score with identity. Include one ordinary case, one boundary and one deliberate failure caused by raising NotImplemented or returning NotImplementedError. 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: NotImplemented is a return sentinel for binary protocol negotiation; NotImplementedError is an exception for an unimplemented API. It shows a trace, not only a final value. The ordinary case should demonstrate “The sentinel has type NotImplementedType and is returned, not raised.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Write the exact return statement and inspect the sentinel type. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For NotImplemented is not NotImplementedError, separate the documented Python functools.total_ordering mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.

Previous chapter . Contents . Next chapter

CHAPTER 6 OF 20 . Use the core tools

6. Equality must align with ordering equivalence

Back to contents

If neither a

The high-value mistake in this chapter is declaring objects unequal by identity while ordering them as indistinguishable values. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Test equal-key instances with every rich comparison.

For the Equality must align with ordering equivalence chapter on Python functools.total_ordering, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on declaring objects unequal by identity while ordering them as indistinguishable values. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

a,b=Mark(4),Mark(4)
print(a==b,a<b,a>b,a<=b,a>=b)

Explained result. The coherent results are True, False, False, True and True. 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 fixtures. Predict the rule using sorting scheduled matches with postponed entries. 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 “If neither a

Case 2: home budget. Contrast the rule using comparing money values only within a currency. 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 “If neither a

Case 3: revision cards. Stress-test the rule using ordering priorities with explicit tie breakers. 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 “If neither a

Case 4: data import. Explain the rule using rejecting incompatible or incomplete external records. 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 “If neither a

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 declaring objects unequal by identity while ordering them as indistinguishable values.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Test equal-key instances with every rich comparison.” 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 Python functools.total_ordering syntax. For this chapter, useful prompts are: “What did you expect from Equality must align with ordering equivalence?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing declaring objects unequal by identity while ordering them as indistinguishable values be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny CCA fixtures with sorting scheduled matches with postponed entries. Include one ordinary case, one boundary and one deliberate failure caused by declaring objects unequal by identity while ordering them as indistinguishable values. 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: If neither a

Decision and transfer

For Equality must align with ordering equivalence, separate the documented Python functools.total_ordering mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.

Previous chapter . Contents . Next chapter

CHAPTER 7 OF 20 . Use the core tools

7. Derived methods preserve operand direction

Back to contents

Generated comparisons combine the root method and equality with the correct reversed relationship; they are not textual aliases. 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 generated __gt__ simply calls self.__lt__(other). It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Trace a>b and b

For the Derived methods preserve operand direction chapter on Python functools.total_ordering, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on assuming generated __gt__ simply calls self.__lt__(other). Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

a,b=Mark(5),Mark(2)
print(a>b,b<a)

Four purposeful transfer cases

Case 1: revision cards. Contrast the rule using ordering priorities with explicit tie breakers. 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.

Case 2: data import. Stress-test the rule using rejecting incompatible or incomplete external records. 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.

Case 3: test laboratory. Explain the rule using checking reflexivity, antisymmetry, transitivity and totality. 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.

Case 4: design review. Transfer the rule using comparing total_ordering, manual methods, dataclasses and key functions. 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.

Diagnostic route

A parent does not need to know the final Python functools.total_ordering syntax. For this chapter, useful prompts are: “What did you expect from Derived methods preserve operand direction?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing assuming generated __gt__ simply calls self.__lt__(other) be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny home budget with comparing money values only within a currency. Include one ordinary case, one boundary and one deliberate failure caused by assuming generated __gt__ simply calls self.__lt__(other). Predict each result before using a tool, then report the first point where observation differs from prediction.

Decision and transfer

For Derived methods preserve operand direction, separate the documented Python functools.total_ordering mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.

Previous chapter . Contents . Next chapter

CHAPTER 8 OF 20 . Use the core tools

8. Inheritance can block method generation

Back to contents

The decorator does not override comparison methods declared on the class or a superclass, even if one is abstract. 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 decoration to replace an inherited unsuitable operator. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Inspect each method through the MRO before assuming which implementation runs.

For the Inheritance can block method generation chapter on Python functools.total_ordering, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on expecting decoration to replace an inherited unsuitable operator. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

print(Mark.__le__.__qualname__)

Explained result. The qualified name reveals the installed owner; an inherited method would keep its slot. 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: test laboratory. Stress-test the rule using checking reflexivity, antisymmetry, transitivity and totality. 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 does not override comparison methods declared on the class or a superclass, even if one is abstract.” Apply this procedure: Inspect each method through the MRO before assuming which implementation runs. The expected mechanism is: The qualified name reveals the installed owner; an inherited method would keep its slot. For the test laboratory, add one near-miss that exposes expecting decoration to replace an inherited unsuitable operator. 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: design review. Explain the rule using comparing total_ordering, manual methods, dataclasses and key functions. 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 does not override comparison methods declared on the class or a superclass, even if one is abstract.” Apply this procedure: Inspect each method through the MRO before assuming which implementation runs. The expected mechanism is: The qualified name reveals the installed owner; an inherited method would keep its slot. For the design review, add one near-miss that exposes expecting decoration to replace an inherited unsuitable operator. 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: library loans. Transfer the rule using ordering due dates while preserving identity and overdue status. 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 does not override comparison methods declared on the class or a superclass, even if one is abstract.” Apply this procedure: Inspect each method through the MRO before assuming which implementation runs. The expected mechanism is: The qualified name reveals the installed owner; an inherited method would keep its slot. For the library loans, add one near-miss that exposes expecting decoration to replace an inherited unsuitable operator. 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: student projects. Predict the rule using ranking immutable version records without confusing score with identity. 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 does not override comparison methods declared on the class or a superclass, even if one is abstract.” Apply this procedure: Inspect each method through the MRO before assuming which implementation runs. The expected mechanism is: The qualified name reveals the installed owner; an inherited method would keep its slot. For the student projects, add one near-miss that exposes expecting decoration to replace an inherited unsuitable operator. 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 decoration to replace an inherited unsuitable operator.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Inspect each method through the MRO before assuming which implementation runs.” 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 Python functools.total_ordering syntax. For this chapter, useful prompts are: “What did you expect from Inheritance can block method generation?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing expecting decoration to replace an inherited unsuitable operator be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny revision cards with ordering priorities with explicit tie breakers. Include one ordinary case, one boundary and one deliberate failure caused by expecting decoration to replace an inherited unsuitable operator. 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 does not override comparison methods declared on the class or a superclass, even if one is abstract. It shows a trace, not only a final value. The ordinary case should demonstrate “The qualified name reveals the installed owner; an inherited method would keep its slot.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Inspect each method through the MRO before assuming which implementation runs. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Inheritance can block method generation, separate the documented Python functools.total_ordering mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.

Previous chapter . Contents . Next chapter

CHAPTER 9 OF 20 . Handle boundaries

9. Decorate the class whose method set you intend to complete

Back to contents

Applying total_ordering at different inheritance layers changes which missing methods are considered. 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 decorating an arbitrary layer and overlooking inherited behaviour. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Draw the MRO and annotate where every rich comparison is defined.

For the Decorate the class whose method set you intend to complete chapter on Python functools.total_ordering, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on decorating an arbitrary layer and overlooking inherited behaviour. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

print([c.__name__ for c in Mark.__mro__])

Explained result. The MRO shows the resolution path used for comparison methods. 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: library loans. Explain the rule using ordering due dates while preserving identity and overdue status. 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 “Applying total_ordering at different inheritance layers changes which missing methods are considered.” Apply this procedure: Draw the MRO and annotate where every rich comparison is defined. The expected mechanism is: The MRO shows the resolution path used for comparison methods. For the library loans, add one near-miss that exposes decorating an arbitrary layer and overlooking inherited behaviour. 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: student projects. Transfer the rule using ranking immutable version records without confusing score with identity. 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 “Applying total_ordering at different inheritance layers changes which missing methods are considered.” Apply this procedure: Draw the MRO and annotate where every rich comparison is defined. The expected mechanism is: The MRO shows the resolution path used for comparison methods. For the student projects, add one near-miss that exposes decorating an arbitrary layer and overlooking inherited behaviour. 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 fixtures. Predict the rule using sorting scheduled matches with postponed entries. 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 “Applying total_ordering at different inheritance layers changes which missing methods are considered.” Apply this procedure: Draw the MRO and annotate where every rich comparison is defined. The expected mechanism is: The MRO shows the resolution path used for comparison methods. For the CCA fixtures, add one near-miss that exposes decorating an arbitrary layer and overlooking inherited behaviour. 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: home budget. Contrast the rule using comparing money values only within a currency. 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 “Applying total_ordering at different inheritance layers changes which missing methods are considered.” Apply this procedure: Draw the MRO and annotate where every rich comparison is defined. The expected mechanism is: The MRO shows the resolution path used for comparison methods. For the home budget, add one near-miss that exposes decorating an arbitrary layer and overlooking inherited behaviour. 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 decorating an arbitrary layer and overlooking inherited behaviour.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Draw the MRO and annotate where every rich comparison is defined.” 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 Python functools.total_ordering syntax. For this chapter, useful prompts are: “What did you expect from Decorate the class whose method set you intend to complete?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing decorating an arbitrary layer and overlooking inherited behaviour be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny data import with rejecting incompatible or incomplete external records. Include one ordinary case, one boundary and one deliberate failure caused by decorating an arbitrary layer and overlooking inherited behaviour. 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: Applying total_ordering at different inheritance layers changes which missing methods are considered. It shows a trace, not only a final value. The ordinary case should demonstrate “The MRO shows the resolution path used for comparison methods.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Draw the MRO and annotate where every rich comparison is defined. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Decorate the class whose method set you intend to complete, separate the documented Python functools.total_ordering mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.

Previous chapter . Contents . Next chapter

CHAPTER 10 OF 20 . Handle boundaries

10. Hashability follows equality rules, not the decorator

Back to contents

Defining value equality generally makes mutable instances unhashable unless a compatible __hash__ is deliberately supplied. 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 total_ordering also creates a safe hash. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Check __hash__ and attempt set insertion before using instances as keys.

For the Hashability follows equality rules, not the decorator chapter on Python functools.total_ordering, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on assuming total_ordering also creates a safe hash. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

print(Mark.__hash__)
try: print({Mark(1)})
except TypeError as e: print(type(e).__name__)

Explained result. __hash__ is None and set insertion fails because equality exists without a stable hash. 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 fixtures. Transfer the rule using sorting scheduled matches with postponed entries. 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 “Defining value equality generally makes mutable instances unhashable unless a compatible __hash__ is deliberately supplied.” Apply this procedure: Check __hash__ and attempt set insertion before using instances as keys. The expected mechanism is: __hash__ is None and set insertion fails because equality exists without a stable hash. For the CCA fixtures, add one near-miss that exposes assuming total_ordering also creates a safe hash. 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: home budget. Predict the rule using comparing money values only within a currency. 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 “Defining value equality generally makes mutable instances unhashable unless a compatible __hash__ is deliberately supplied.” Apply this procedure: Check __hash__ and attempt set insertion before using instances as keys. The expected mechanism is: __hash__ is None and set insertion fails because equality exists without a stable hash. For the home budget, add one near-miss that exposes assuming total_ordering also creates a safe hash. 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 cards. Contrast the rule using ordering priorities with explicit tie breakers. 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 “Defining value equality generally makes mutable instances unhashable unless a compatible __hash__ is deliberately supplied.” Apply this procedure: Check __hash__ and attempt set insertion before using instances as keys. The expected mechanism is: __hash__ is None and set insertion fails because equality exists without a stable hash. For the revision cards, add one near-miss that exposes assuming total_ordering also creates a safe hash. 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: data import. Stress-test the rule using rejecting incompatible or incomplete external records. 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 “Defining value equality generally makes mutable instances unhashable unless a compatible __hash__ is deliberately supplied.” Apply this procedure: Check __hash__ and attempt set insertion before using instances as keys. The expected mechanism is: __hash__ is None and set insertion fails because equality exists without a stable hash. For the data import, add one near-miss that exposes assuming total_ordering also creates a safe hash. 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 total_ordering also creates a safe hash.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Check __hash__ and attempt set insertion before using instances as keys.” 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 Python functools.total_ordering syntax. For this chapter, useful prompts are: “What did you expect from Hashability follows equality rules, not the decorator?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing assuming total_ordering also creates a safe hash be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny test laboratory with checking reflexivity, antisymmetry, transitivity and totality. Include one ordinary case, one boundary and one deliberate failure caused by assuming total_ordering also creates a safe hash. 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: Defining value equality generally makes mutable instances unhashable unless a compatible __hash__ is deliberately supplied. It shows a trace, not only a final value. The ordinary case should demonstrate “__hash__ is None and set insertion fails because equality exists without a stable hash.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Check __hash__ and attempt set insertion before using instances as keys. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Hashability follows equality rules, not the decorator, separate the documented Python functools.total_ordering mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.

Previous chapter . Contents . Next chapter

CHAPTER 11 OF 20 . Handle boundaries

11. Mutable comparison keys are hazardous

Back to contents

Changing a field used for order can invalidate a sorted list, heap or bisect invariant. 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 once and treating later mutation as automatically re-sorted. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Sort, mutate one key and compare stored position with a fresh sort.

For the Mutable comparison keys are hazardous chapter on Python functools.total_ordering, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on sorting once and treating later mutation as automatically re-sorted. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

items=[Mark(1),Mark(3)]
items.sort(); items[0].n=9
print([x.n for x in items])

Explained result. The list remains [9,3]; mutation did not preserve sorted 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 cards. Predict the rule using ordering priorities with explicit tie breakers. 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 “Changing a field used for order can invalidate a sorted list, heap or bisect invariant.” Apply this procedure: Sort, mutate one key and compare stored position with a fresh sort. The expected mechanism is: The list remains [9,3]; mutation did not preserve sorted order. For the revision cards, add one near-miss that exposes sorting once and treating later mutation as automatically re-sorted. 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: data import. Contrast the rule using rejecting incompatible or incomplete external records. 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 “Changing a field used for order can invalidate a sorted list, heap or bisect invariant.” Apply this procedure: Sort, mutate one key and compare stored position with a fresh sort. The expected mechanism is: The list remains [9,3]; mutation did not preserve sorted order. For the data import, add one near-miss that exposes sorting once and treating later mutation as automatically re-sorted. 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: test laboratory. Stress-test the rule using checking reflexivity, antisymmetry, transitivity and totality. 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 “Changing a field used for order can invalidate a sorted list, heap or bisect invariant.” Apply this procedure: Sort, mutate one key and compare stored position with a fresh sort. The expected mechanism is: The list remains [9,3]; mutation did not preserve sorted order. For the test laboratory, add one near-miss that exposes sorting once and treating later mutation as automatically re-sorted. 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: design review. Explain the rule using comparing total_ordering, manual methods, dataclasses and key functions. 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 “Changing a field used for order can invalidate a sorted list, heap or bisect invariant.” Apply this procedure: Sort, mutate one key and compare stored position with a fresh sort. The expected mechanism is: The list remains [9,3]; mutation did not preserve sorted order. For the design review, add one near-miss that exposes sorting once and treating later mutation as automatically re-sorted. 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 once and treating later mutation as automatically re-sorted.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Sort, mutate one key and compare stored position with a fresh sort.” 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 Python functools.total_ordering syntax. For this chapter, useful prompts are: “What did you expect from Mutable comparison keys are hazardous?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing sorting once and treating later mutation as automatically re-sorted be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny design review with comparing total_ordering, manual methods, dataclasses and key functions. Include one ordinary case, one boundary and one deliberate failure caused by sorting once and treating later mutation as automatically re-sorted. 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: Changing a field used for order can invalidate a sorted list, heap or bisect invariant. It shows a trace, not only a final value. The ordinary case should demonstrate “The list remains [9,3]; mutation did not preserve sorted order.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Sort, mutate one key and compare stored position with a fresh sort. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Mutable comparison keys are hazardous, separate the documented Python functools.total_ordering mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.

Previous chapter . Contents . Next chapter

CHAPTER 12 OF 20 . Handle boundaries

12. dataclass order is a different generator

Back to contents

dataclass(order=True) derives tuple-like comparisons from declared comparable fields and also generates equality unless configured otherwise. 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 stacking dataclass ordering and total_ordering without deciding ownership. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Choose one generator and inspect which fields participate.

For the dataclass order is a different generator chapter on Python functools.total_ordering, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on stacking dataclass ordering and total_ordering without deciding ownership. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from dataclasses import dataclass
@dataclass(order=True)
class Point: x:int; y:int
print(Point(1,9)<Point(2,0))

Explained result. The result is True because dataclass comparison uses x then y. 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: test laboratory. Contrast the rule using checking reflexivity, antisymmetry, transitivity and totality. 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(order=True) derives tuple-like comparisons from declared comparable fields and also generates equality unless configured otherwise.” Apply this procedure: Choose one generator and inspect which fields participate. The expected mechanism is: The result is True because dataclass comparison uses x then y. For the test laboratory, add one near-miss that exposes stacking dataclass ordering and total_ordering without deciding ownership. 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: design review. Stress-test the rule using comparing total_ordering, manual methods, dataclasses and key functions. 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(order=True) derives tuple-like comparisons from declared comparable fields and also generates equality unless configured otherwise.” Apply this procedure: Choose one generator and inspect which fields participate. The expected mechanism is: The result is True because dataclass comparison uses x then y. For the design review, add one near-miss that exposes stacking dataclass ordering and total_ordering without deciding ownership. 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: library loans. Explain the rule using ordering due dates while preserving identity and overdue status. 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(order=True) derives tuple-like comparisons from declared comparable fields and also generates equality unless configured otherwise.” Apply this procedure: Choose one generator and inspect which fields participate. The expected mechanism is: The result is True because dataclass comparison uses x then y. For the library loans, add one near-miss that exposes stacking dataclass ordering and total_ordering without deciding ownership. 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: student projects. Transfer the rule using ranking immutable version records without confusing score with identity. 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(order=True) derives tuple-like comparisons from declared comparable fields and also generates equality unless configured otherwise.” Apply this procedure: Choose one generator and inspect which fields participate. The expected mechanism is: The result is True because dataclass comparison uses x then y. For the student projects, add one near-miss that exposes stacking dataclass ordering and total_ordering without deciding ownership. 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 stacking dataclass ordering and total_ordering without deciding ownership.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Choose one generator and inspect which fields participate.” 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 Python functools.total_ordering syntax. For this chapter, useful prompts are: “What did you expect from dataclass order is a different generator?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing stacking dataclass ordering and total_ordering without deciding ownership be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny library loans with ordering due dates while preserving identity and overdue status. Include one ordinary case, one boundary and one deliberate failure caused by stacking dataclass ordering and total_ordering without deciding ownership. 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(order=True) derives tuple-like comparisons from declared comparable fields and also generates equality unless configured otherwise. It shows a trace, not only a final value. The ordinary case should demonstrate “The result is True because dataclass comparison uses x then y.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Choose one generator and inspect which fields participate. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For dataclass order is a different generator, separate the documented Python functools.total_ordering mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.

Previous chapter . Contents . Next chapter

CHAPTER 13 OF 20 . Debug and verify

13. Key functions may be the better design

Back to contents

sorted(key=…) localises a presentation order when an object has no single universal natural order. 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 embedding one report-specific order into every comparison. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Sort records by two named keys and state the decision each serves.

For the Key functions may be the better design chapter on Python functools.total_ordering, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on embedding one report-specific order into every comparison. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

rows=[{'name':'B','score':9},{'name':'A','score':7}]
print([r['name'] for r in sorted(rows,key=lambda r:r['name'])])

Explained result. The explicit name key yields A then B without claiming all records are naturally ordered by name. 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: library loans. Stress-test the rule using ordering due dates while preserving identity and overdue status. 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 “sorted(key=…) localises a presentation order when an object has no single universal natural order.” Apply this procedure: Sort records by two named keys and state the decision each serves. The expected mechanism is: The explicit name key yields A then B without claiming all records are naturally ordered by name. For the library loans, add one near-miss that exposes embedding one report-specific order into every comparison. 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: student projects. Explain the rule using ranking immutable version records without confusing score with identity. 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 “sorted(key=…) localises a presentation order when an object has no single universal natural order.” Apply this procedure: Sort records by two named keys and state the decision each serves. The expected mechanism is: The explicit name key yields A then B without claiming all records are naturally ordered by name. For the student projects, add one near-miss that exposes embedding one report-specific order into every comparison. 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 fixtures. Transfer the rule using sorting scheduled matches with postponed entries. 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 “sorted(key=…) localises a presentation order when an object has no single universal natural order.” Apply this procedure: Sort records by two named keys and state the decision each serves. The expected mechanism is: The explicit name key yields A then B without claiming all records are naturally ordered by name. For the CCA fixtures, add one near-miss that exposes embedding one report-specific order into every comparison. 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: home budget. Predict the rule using comparing money values only within a currency. 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 “sorted(key=…) localises a presentation order when an object has no single universal natural order.” Apply this procedure: Sort records by two named keys and state the decision each serves. The expected mechanism is: The explicit name key yields A then B without claiming all records are naturally ordered by name. For the home budget, add one near-miss that exposes embedding one report-specific order into every comparison. 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 embedding one report-specific order into every comparison.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Sort records by two named keys and state the decision each serves.” 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 Python functools.total_ordering syntax. For this chapter, useful prompts are: “What did you expect from Key functions may be the better design?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing embedding one report-specific order into every comparison be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny student projects with ranking immutable version records without confusing score with identity. Include one ordinary case, one boundary and one deliberate failure caused by embedding one report-specific order into every comparison. 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: sorted(key=…) localises a presentation order when an object has no single universal natural order. It shows a trace, not only a final value. The ordinary case should demonstrate “The explicit name key yields A then B without claiming all records are naturally ordered by name.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Sort records by two named keys and state the decision each serves. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Key functions may be the better design, separate the documented Python functools.total_ordering mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.

Previous chapter . Contents . Next chapter

CHAPTER 14 OF 20 . Debug and verify

14. Partial orders do not become total by decoration

Back to contents

Sets, dependency relations and interval overlap can contain incomparable pairs; a decorator cannot repair the domain. 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 incomparable states into arbitrary less-than results. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Find a pair for which neither direction is semantically lower and model that relation separately.

For the Partial orders do not become total by decoration chapter on Python functools.total_ordering, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on forcing incomparable states into arbitrary less-than results. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

a,b={1,2},{2,3}
print(a<=b,b<=a)

Explained result. Both are False because subset is a partial order and the sets are incomparable. 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 fixtures. Explain the rule using sorting scheduled matches with postponed entries. 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 “Sets, dependency relations and interval overlap can contain incomparable pairs; a decorator cannot repair the domain.” Apply this procedure: Find a pair for which neither direction is semantically lower and model that relation separately. The expected mechanism is: Both are False because subset is a partial order and the sets are incomparable. For the CCA fixtures, add one near-miss that exposes forcing incomparable states into arbitrary less-than results. 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: home budget. Transfer the rule using comparing money values only within a currency. 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 “Sets, dependency relations and interval overlap can contain incomparable pairs; a decorator cannot repair the domain.” Apply this procedure: Find a pair for which neither direction is semantically lower and model that relation separately. The expected mechanism is: Both are False because subset is a partial order and the sets are incomparable. For the home budget, add one near-miss that exposes forcing incomparable states into arbitrary less-than results. 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 cards. Predict the rule using ordering priorities with explicit tie breakers. 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 “Sets, dependency relations and interval overlap can contain incomparable pairs; a decorator cannot repair the domain.” Apply this procedure: Find a pair for which neither direction is semantically lower and model that relation separately. The expected mechanism is: Both are False because subset is a partial order and the sets are incomparable. For the revision cards, add one near-miss that exposes forcing incomparable states into arbitrary less-than results. 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: data import. Contrast the rule using rejecting incompatible or incomplete external records. 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 “Sets, dependency relations and interval overlap can contain incomparable pairs; a decorator cannot repair the domain.” Apply this procedure: Find a pair for which neither direction is semantically lower and model that relation separately. The expected mechanism is: Both are False because subset is a partial order and the sets are incomparable. For the data import, add one near-miss that exposes forcing incomparable states into arbitrary less-than results. 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 incomparable states into arbitrary less-than results.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Find a pair for which neither direction is semantically lower and model that relation separately.” 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 Python functools.total_ordering syntax. For this chapter, useful prompts are: “What did you expect from Partial orders do not become total by decoration?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing forcing incomparable states into arbitrary less-than results be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny CCA fixtures with sorting scheduled matches with postponed entries. Include one ordinary case, one boundary and one deliberate failure caused by forcing incomparable states into arbitrary less-than results. 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: Sets, dependency relations and interval overlap can contain incomparable pairs; a decorator cannot repair the domain. It shows a trace, not only a final value. The ordinary case should demonstrate “Both are False because subset is a partial order and the sets are incomparable.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Find a pair for which neither direction is semantically lower and model that relation separately. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Partial orders do not become total by decoration, separate the documented Python functools.total_ordering mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.

Previous chapter . Contents . Next chapter

CHAPTER 15 OF 20 . Debug and verify

15. NaN exposes difficult order semantics

Back to contents

Floating NaN is unequal to itself and neither less nor greater, so it can violate assumptions of a total order. 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 allowing NaN into a key without an explicit missing-value policy. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Test self equality and both directions, then reject, normalise or segregate.

For the NaN exposes difficult order semantics chapter on Python functools.total_ordering, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on allowing NaN into a key without an explicit missing-value policy. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

x=float('nan')
print(x==x,x<x,x>x)

Explained result. All three are False, so a total-order domain needs an explicit NaN policy. 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 cards. Transfer the rule using ordering priorities with explicit tie breakers. 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 “Floating NaN is unequal to itself and neither less nor greater, so it can violate assumptions of a total order.” Apply this procedure: Test self equality and both directions, then reject, normalise or segregate. The expected mechanism is: All three are False, so a total-order domain needs an explicit NaN policy. For the revision cards, add one near-miss that exposes allowing NaN into a key without an explicit missing-value policy. 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: data import. Predict the rule using rejecting incompatible or incomplete external records. 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 “Floating NaN is unequal to itself and neither less nor greater, so it can violate assumptions of a total order.” Apply this procedure: Test self equality and both directions, then reject, normalise or segregate. The expected mechanism is: All three are False, so a total-order domain needs an explicit NaN policy. For the data import, add one near-miss that exposes allowing NaN into a key without an explicit missing-value policy. 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: test laboratory. Contrast the rule using checking reflexivity, antisymmetry, transitivity and totality. 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 “Floating NaN is unequal to itself and neither less nor greater, so it can violate assumptions of a total order.” Apply this procedure: Test self equality and both directions, then reject, normalise or segregate. The expected mechanism is: All three are False, so a total-order domain needs an explicit NaN policy. For the test laboratory, add one near-miss that exposes allowing NaN into a key without an explicit missing-value policy. 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: design review. Stress-test the rule using comparing total_ordering, manual methods, dataclasses and key functions. 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 “Floating NaN is unequal to itself and neither less nor greater, so it can violate assumptions of a total order.” Apply this procedure: Test self equality and both directions, then reject, normalise or segregate. The expected mechanism is: All three are False, so a total-order domain needs an explicit NaN policy. For the design review, add one near-miss that exposes allowing NaN into a key without an explicit missing-value policy. 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 allowing NaN into a key without an explicit missing-value policy.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Test self equality and both directions, then reject, normalise or segregate.” 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 Python functools.total_ordering syntax. For this chapter, useful prompts are: “What did you expect from NaN exposes difficult order semantics?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing allowing NaN into a key without an explicit missing-value policy be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny home budget with comparing money values only within a currency. Include one ordinary case, one boundary and one deliberate failure caused by allowing NaN into a key without an explicit missing-value policy. 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: Floating NaN is unequal to itself and neither less nor greater, so it can violate assumptions of a total order. It shows a trace, not only a final value. The ordinary case should demonstrate “All three are False, so a total-order domain needs an explicit NaN policy.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Test self equality and both directions, then reject, normalise or segregate. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For NaN exposes difficult order semantics, separate the documented Python functools.total_ordering mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.

Previous chapter . Contents . Next chapter

CHAPTER 16 OF 20 . Debug and verify

16. Generated methods cost calls and stack frames

Back to contents

Official documentation notes slower execution and more complex stack traces for derived comparisons than hand-written 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 treating decorator convenience as zero-cost or optimising without measurement. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Benchmark the real hot path and inspect one traceback before replacing readable code.

For the Generated methods cost calls and stack frames chapter on Python functools.total_ordering, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on treating decorator convenience as zero-cost or optimising without measurement. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

import inspect
print(inspect.getsourcefile(Mark.__le__))

Explained result. The generated method comes from functools infrastructure; profiling decides whether that matters. 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: test laboratory. Predict the rule using checking reflexivity, antisymmetry, transitivity and totality. 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 “Official documentation notes slower execution and more complex stack traces for derived comparisons than hand-written methods.” Apply this procedure: Benchmark the real hot path and inspect one traceback before replacing readable code. The expected mechanism is: The generated method comes from functools infrastructure; profiling decides whether that matters. For the test laboratory, add one near-miss that exposes treating decorator convenience as zero-cost or optimising without measurement. 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: design review. Contrast the rule using comparing total_ordering, manual methods, dataclasses and key functions. 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 “Official documentation notes slower execution and more complex stack traces for derived comparisons than hand-written methods.” Apply this procedure: Benchmark the real hot path and inspect one traceback before replacing readable code. The expected mechanism is: The generated method comes from functools infrastructure; profiling decides whether that matters. For the design review, add one near-miss that exposes treating decorator convenience as zero-cost or optimising without measurement. 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: library loans. Stress-test the rule using ordering due dates while preserving identity and overdue status. 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 “Official documentation notes slower execution and more complex stack traces for derived comparisons than hand-written methods.” Apply this procedure: Benchmark the real hot path and inspect one traceback before replacing readable code. The expected mechanism is: The generated method comes from functools infrastructure; profiling decides whether that matters. For the library loans, add one near-miss that exposes treating decorator convenience as zero-cost or optimising without measurement. 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: student projects. Explain the rule using ranking immutable version records without confusing score with identity. 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 “Official documentation notes slower execution and more complex stack traces for derived comparisons than hand-written methods.” Apply this procedure: Benchmark the real hot path and inspect one traceback before replacing readable code. The expected mechanism is: The generated method comes from functools infrastructure; profiling decides whether that matters. For the student projects, add one near-miss that exposes treating decorator convenience as zero-cost or optimising without measurement. 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 decorator convenience as zero-cost or optimising without measurement.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Benchmark the real hot path and inspect one traceback before replacing readable code.” 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 Python functools.total_ordering syntax. For this chapter, useful prompts are: “What did you expect from Generated methods cost calls and stack frames?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing treating decorator convenience as zero-cost or optimising without measurement be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny revision cards with ordering priorities with explicit tie breakers. Include one ordinary case, one boundary and one deliberate failure caused by treating decorator convenience as zero-cost or optimising without measurement. 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: Official documentation notes slower execution and more complex stack traces for derived comparisons than hand-written methods. It shows a trace, not only a final value. The ordinary case should demonstrate “The generated method comes from functools infrastructure; profiling decides whether that matters.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Benchmark the real hot path and inspect one traceback before replacing readable code. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Generated methods cost calls and stack frames, separate the documented Python functools.total_ordering mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.

Previous chapter . Contents . Next chapter

CHAPTER 17 OF 20 . Transfer with judgment

17. Law tests reveal contradictions

Back to contents

Test reflexivity of <=, antisymmetry, transitivity, comparability and consistency with == across representative values. 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 testing only one ascending happy path. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Generate triples including ties and boundaries and report the smallest counterexample.

For the Law tests reveal contradictions chapter on Python functools.total_ordering, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on testing only one ascending happy path. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

vals=[Mark(n) for n in [0,1,1,2]]
print(all(a<=a for a in vals))

Explained result. Reflexivity passes for these values; every other law still needs its own test. 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: library loans. Contrast the rule using ordering due dates while preserving identity and overdue status. 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 “Test reflexivity of <=, antisymmetry, transitivity, comparability and consistency with == across representative values.” Apply this procedure: Generate triples including ties and boundaries and report the smallest counterexample. The expected mechanism is: Reflexivity passes for these values; every other law still needs its own test. For the library loans, add one near-miss that exposes testing only one ascending happy path. 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: student projects. Stress-test the rule using ranking immutable version records without confusing score with identity. 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 “Test reflexivity of <=, antisymmetry, transitivity, comparability and consistency with == across representative values.” Apply this procedure: Generate triples including ties and boundaries and report the smallest counterexample. The expected mechanism is: Reflexivity passes for these values; every other law still needs its own test. For the student projects, add one near-miss that exposes testing only one ascending happy path. 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 fixtures. Explain the rule using sorting scheduled matches with postponed entries. 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 “Test reflexivity of <=, antisymmetry, transitivity, comparability and consistency with == across representative values.” Apply this procedure: Generate triples including ties and boundaries and report the smallest counterexample. The expected mechanism is: Reflexivity passes for these values; every other law still needs its own test. For the CCA fixtures, add one near-miss that exposes testing only one ascending happy path. 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: home budget. Transfer the rule using comparing money values only within a currency. 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 “Test reflexivity of <=, antisymmetry, transitivity, comparability and consistency with == across representative values.” Apply this procedure: Generate triples including ties and boundaries and report the smallest counterexample. The expected mechanism is: Reflexivity passes for these values; every other law still needs its own test. For the home budget, add one near-miss that exposes testing only one ascending happy path. 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 testing only one ascending happy path.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Generate triples including ties and boundaries and report the smallest counterexample.” 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 Python functools.total_ordering syntax. For this chapter, useful prompts are: “What did you expect from Law tests reveal contradictions?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing testing only one ascending happy path be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny data import with rejecting incompatible or incomplete external records. Include one ordinary case, one boundary and one deliberate failure caused by testing only one ascending happy path. 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: Test reflexivity of <=, antisymmetry, transitivity, comparability and consistency with == across representative values. It shows a trace, not only a final value. The ordinary case should demonstrate “Reflexivity passes for these values; every other law still needs its own test.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Generate triples including ties and boundaries and report the smallest counterexample. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Law tests reveal contradictions, separate the documented Python functools.total_ordering mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.

Previous chapter . Contents . Next chapter

CHAPTER 18 OF 20 . Transfer with judgment

18. Foreign types belong in the test matrix

Back to contents

A robust suite covers same-type values, subclasses, unsupported operands, missing values and mutation boundaries. 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 TypeError on a foreign operand as irrelevant. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Build an operand-category matrix and predict boolean, reflected handling or exception.

For the Foreign types belong in the test matrix chapter on Python functools.total_ordering, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on treating TypeError on a foreign operand as irrelevant. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

for other in [None,'2',2.0]:
 try: print(Mark(2)<other)
 except TypeError: print('TypeError')

Explained result. Every unsupported operand follows the chosen boundary instead of a fabricated 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: CCA fixtures. Stress-test the rule using sorting scheduled matches with postponed entries. 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 robust suite covers same-type values, subclasses, unsupported operands, missing values and mutation boundaries.” Apply this procedure: Build an operand-category matrix and predict boolean, reflected handling or exception. The expected mechanism is: Every unsupported operand follows the chosen boundary instead of a fabricated order. For the CCA fixtures, add one near-miss that exposes treating TypeError on a foreign operand as irrelevant. 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: home budget. Explain the rule using comparing money values only within a currency. 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 robust suite covers same-type values, subclasses, unsupported operands, missing values and mutation boundaries.” Apply this procedure: Build an operand-category matrix and predict boolean, reflected handling or exception. The expected mechanism is: Every unsupported operand follows the chosen boundary instead of a fabricated order. For the home budget, add one near-miss that exposes treating TypeError on a foreign operand as irrelevant. 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 cards. Transfer the rule using ordering priorities with explicit tie breakers. 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 robust suite covers same-type values, subclasses, unsupported operands, missing values and mutation boundaries.” Apply this procedure: Build an operand-category matrix and predict boolean, reflected handling or exception. The expected mechanism is: Every unsupported operand follows the chosen boundary instead of a fabricated order. For the revision cards, add one near-miss that exposes treating TypeError on a foreign operand as irrelevant. 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: data import. Predict the rule using rejecting incompatible or incomplete external records. 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 robust suite covers same-type values, subclasses, unsupported operands, missing values and mutation boundaries.” Apply this procedure: Build an operand-category matrix and predict boolean, reflected handling or exception. The expected mechanism is: Every unsupported operand follows the chosen boundary instead of a fabricated order. For the data import, add one near-miss that exposes treating TypeError on a foreign operand as irrelevant. 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 TypeError on a foreign operand as irrelevant.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Build an operand-category matrix and predict boolean, reflected handling or exception.” 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 Python functools.total_ordering syntax. For this chapter, useful prompts are: “What did you expect from Foreign types belong in the test matrix?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing treating TypeError on a foreign operand as irrelevant be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny test laboratory with checking reflexivity, antisymmetry, transitivity and totality. Include one ordinary case, one boundary and one deliberate failure caused by treating TypeError on a foreign operand as irrelevant. 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 robust suite covers same-type values, subclasses, unsupported operands, missing values and mutation boundaries. It shows a trace, not only a final value. The ordinary case should demonstrate “Every unsupported operand follows the chosen boundary instead of a fabricated order.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Build an operand-category matrix and predict boolean, reflected handling or exception. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Foreign types belong in the test matrix, separate the documented Python functools.total_ordering mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.

Previous chapter . Contents . Next chapter

CHAPTER 19 OF 20 . Transfer with judgment

19. Stable sorting preserves equal-key input order

Back to contents

Python sorting is stable, so records equal under the comparison retain relative order. 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 a fake identity tie breaker when stable grouping is desired. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Label equal-key records, sort and verify label order.

For the Stable sorting preserves equal-key input order chapter on Python functools.total_ordering, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on adding a fake identity tie breaker when stable grouping is desired. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

pairs=[(2,'first'),(1,'x'),(2,'second')]
print(sorted(pairs,key=lambda p:p[0]))

Explained result. The two key-2 records remain first then second after the key-1 record. 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 cards. Explain the rule using ordering priorities with explicit tie breakers. 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 “Python sorting is stable, so records equal under the comparison retain relative order.” Apply this procedure: Label equal-key records, sort and verify label order. The expected mechanism is: The two key-2 records remain first then second after the key-1 record. For the revision cards, add one near-miss that exposes adding a fake identity tie breaker when stable grouping is desired. 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: data import. Transfer the rule using rejecting incompatible or incomplete external records. 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 “Python sorting is stable, so records equal under the comparison retain relative order.” Apply this procedure: Label equal-key records, sort and verify label order. The expected mechanism is: The two key-2 records remain first then second after the key-1 record. For the data import, add one near-miss that exposes adding a fake identity tie breaker when stable grouping is desired. 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: test laboratory. Predict the rule using checking reflexivity, antisymmetry, transitivity and totality. 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 “Python sorting is stable, so records equal under the comparison retain relative order.” Apply this procedure: Label equal-key records, sort and verify label order. The expected mechanism is: The two key-2 records remain first then second after the key-1 record. For the test laboratory, add one near-miss that exposes adding a fake identity tie breaker when stable grouping is desired. 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: design review. Contrast the rule using comparing total_ordering, manual methods, dataclasses and key functions. 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 “Python sorting is stable, so records equal under the comparison retain relative order.” Apply this procedure: Label equal-key records, sort and verify label order. The expected mechanism is: The two key-2 records remain first then second after the key-1 record. For the design review, add one near-miss that exposes adding a fake identity tie breaker when stable grouping is desired. 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 a fake identity tie breaker when stable grouping is desired.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Label equal-key records, sort and verify label 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 Python functools.total_ordering syntax. For this chapter, useful prompts are: “What did you expect from Stable sorting preserves equal-key input order?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing adding a fake identity tie breaker when stable grouping is desired be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny design review with comparing total_ordering, manual methods, dataclasses and key functions. Include one ordinary case, one boundary and one deliberate failure caused by adding a fake identity tie breaker when stable grouping is desired. 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: Python sorting is stable, so records equal under the comparison retain relative order. It shows a trace, not only a final value. The ordinary case should demonstrate “The two key-2 records remain first then second after the key-1 record.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Label equal-key records, sort and verify label order. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Stable sorting preserves equal-key input order, separate the documented Python functools.total_ordering mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.

Previous chapter . Contents . Next chapter

CHAPTER 20 OF 20 . Transfer with judgment

20. Choose total_ordering for one honest natural order

Back to contents

The decorator is useful when a compact, tested comparison core expresses the domain; otherwise use explicit keys, dataclasses or named operations. 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 the decorator merely because it reduces typing. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Write invariants, foreign-type policy, mutability and performance needs before selecting the design.

For the Choose total_ordering for one honest natural order chapter on Python functools.total_ordering, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on choosing the decorator merely because it reduces typing. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

def by_due_date(loan): return loan.due_date

Explained result. A named key expresses one workflow order without changing equality for every Loan. 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: test laboratory. Transfer the rule using checking reflexivity, antisymmetry, transitivity and totality. 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 is useful when a compact, tested comparison core expresses the domain; otherwise use explicit keys, dataclasses or named operations.” Apply this procedure: Write invariants, foreign-type policy, mutability and performance needs before selecting the design. The expected mechanism is: A named key expresses one workflow order without changing equality for every Loan. For the test laboratory, add one near-miss that exposes choosing the decorator merely because it reduces typing. 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: design review. Predict the rule using comparing total_ordering, manual methods, dataclasses and key functions. 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 is useful when a compact, tested comparison core expresses the domain; otherwise use explicit keys, dataclasses or named operations.” Apply this procedure: Write invariants, foreign-type policy, mutability and performance needs before selecting the design. The expected mechanism is: A named key expresses one workflow order without changing equality for every Loan. For the design review, add one near-miss that exposes choosing the decorator merely because it reduces typing. 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: library loans. Contrast the rule using ordering due dates while preserving identity and overdue status. 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 is useful when a compact, tested comparison core expresses the domain; otherwise use explicit keys, dataclasses or named operations.” Apply this procedure: Write invariants, foreign-type policy, mutability and performance needs before selecting the design. The expected mechanism is: A named key expresses one workflow order without changing equality for every Loan. For the library loans, add one near-miss that exposes choosing the decorator merely because it reduces typing. 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: student projects. Stress-test the rule using ranking immutable version records without confusing score with identity. 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 is useful when a compact, tested comparison core expresses the domain; otherwise use explicit keys, dataclasses or named operations.” Apply this procedure: Write invariants, foreign-type policy, mutability and performance needs before selecting the design. The expected mechanism is: A named key expresses one workflow order without changing equality for every Loan. For the student projects, add one near-miss that exposes choosing the decorator merely because it reduces typing. 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 the decorator merely because it reduces typing.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Write invariants, foreign-type policy, mutability and performance needs before selecting the design.” 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 Python functools.total_ordering syntax. For this chapter, useful prompts are: “What did you expect from Choose total_ordering for one honest natural order?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing choosing the decorator merely because it reduces typing be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny library loans with ordering due dates while preserving identity and overdue status. Include one ordinary case, one boundary and one deliberate failure caused by choosing the decorator merely because it reduces typing. 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 is useful when a compact, tested comparison core expresses the domain; otherwise use explicit keys, dataclasses or named operations. It shows a trace, not only a final value. The ordinary case should demonstrate “A named key expresses one workflow order without changing equality for every Loan.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Write invariants, foreign-type policy, mutability and performance needs before selecting the design. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Choose total_ordering for one honest natural order, separate the documented Python functools.total_ordering mechanism from the project policy. State exactly what the technical contract guarantees, then state the project choice about validation, ordering, ownership, performance or recovery. Test whether the same distinction survives one transfer case, and keep stateful experiments disposable and backed up.

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. library loans: model, boundary and recovery

Create a small library loans using ordering due dates while preserving identity and overdue status. Combine “The decorator derives missing rich comparisons” 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: A class supplies __eq__ plus one of __lt__, __le__, __gt__ or __ge__; total_ordering synthesises the other ordering methods. Apply: List the supplied methods, generated methods and domain key before running comparisons. Verify: The result is True; __le__ is derived from the two methods whose meaning the class author supplied. 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. student projects: model, boundary and recovery

Create a small student projects using ranking immutable version records without confusing score with identity. Combine “Return NotImplemented for unsupported operands” 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: NotImplemented lets Python try the reflected operation or raise TypeError instead of receiving a misleading boolean. Apply: Compare with one compatible object and one foreign value while tracing the protocol. Verify: The unsupported mixed comparison becomes TypeError rather than pretending the Mark is not lower. 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 fixtures: model, boundary and recovery

Create a small CCA fixtures using sorting scheduled matches with postponed entries. Combine “Derived methods preserve operand direction” 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: Generated comparisons combine the root method and equality with the correct reversed relationship; they are not textual aliases. Apply: Trace a>b and b

4. home budget: model, boundary and recovery

Create a small home budget using comparing money values only within a currency. Combine “Hashability follows equality rules, not the decorator” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.

5. revision cards: model, boundary and recovery

Create a small revision cards using ordering priorities with explicit tie breakers. Combine “Key functions may be the better design” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.

6. data import: model, boundary and recovery

Create a small data import using rejecting incompatible or incomplete external records. Combine “Generated methods cost calls and stack frames” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.

7. test laboratory: model, boundary and recovery

Create a small test laboratory using checking reflexivity, antisymmetry, transitivity and totality. Combine “Stable sorting preserves equal-key input order” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.

8. design review: model, boundary and recovery

Create a small design review using comparing total_ordering, manual methods, dataclasses and key functions. Combine “At least one ordering method is mandatory” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.

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 的更多信息

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

继续阅读