Small Group Tutorials

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

How to Master Python decimal.Context in Punggol Tuition

Student in a blue pinafore smiles with a hand beside the face in a bright corridor.

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 decimal.Context is the arithmetic environment that governs Decimal precision, rounding, exponent limits, status flags and trap enablers. Decimal objects carry values, while the active context controls most arithmetic and records exceptional conditions. Mastery means predicting which operation consults which context, separating construction from arithmetic, choosing a rounding policy deliberately, treating sticky flags as evidence, enabling traps when silent approximation is unacceptable, and containing temporary policy changes with localcontext(). 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. Context is the arithmetic environment

Back to contents

A Context supplies precision, rounding, exponent limits, flags and traps for Decimal operations; it is not the Decimal value itself. 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 changing a Context and expecting already stored coefficients to be rewritten. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Write the value and the active arithmetic policy in separate boxes, then run one operation that requires rounding.

For the Context is the arithmetic environment chapter on Python decimal.Context, 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 changing a Context and expecting already stored coefficients to be rewritten. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from decimal import Decimal, getcontext
getcontext().prec = 4
print(Decimal('1') / Decimal('7'))

Explained result. Division consults the current precision and produces Decimal(‘0.1429’); the input Decimals remain immutable values. 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: canteen budget. Predict the rule using prices, quantities, discounts and a two-place reporting rule. 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 Context supplies precision, rounding, exponent limits, flags and traps for Decimal operations; it is not the Decimal value itself.” Apply this procedure: Write the value and the active arithmetic policy in separate boxes, then run one operation that requires rounding. The expected mechanism is: Division consults the current precision and produces Decimal(‘0.1429’); the input Decimals remain immutable values. For the canteen budget, add one near-miss that exposes changing a Context and expecting already stored coefficients to be rewritten. 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: reading tracker. Contrast the rule using percentage completion calculated under a stated precision. 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 Context supplies precision, rounding, exponent limits, flags and traps for Decimal operations; it is not the Decimal value itself.” Apply this procedure: Write the value and the active arithmetic policy in separate boxes, then run one operation that requires rounding. The expected mechanism is: Division consults the current precision and produces Decimal(‘0.1429’); the input Decimals remain immutable values. For the reading tracker, add one near-miss that exposes changing a Context and expecting already stored coefficients to be rewritten. 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: science practical. Stress-test the rule using measured values with significant digits and an inexact-result audit. 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 Context supplies precision, rounding, exponent limits, flags and traps for Decimal operations; it is not the Decimal value itself.” Apply this procedure: Write the value and the active arithmetic policy in separate boxes, then run one operation that requires rounding. The expected mechanism is: Division consults the current precision and produces Decimal(‘0.1429’); the input Decimals remain immutable values. For the science practical, add one near-miss that exposes changing a Context and expecting already stored coefficients to be rewritten. 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: CCA fundraiser. Explain the rule using cash totals, percentage adjustments and explicit half-up rounding. 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 Context supplies precision, rounding, exponent limits, flags and traps for Decimal operations; it is not the Decimal value itself.” Apply this procedure: Write the value and the active arithmetic policy in separate boxes, then run one operation that requires rounding. The expected mechanism is: Division consults the current precision and produces Decimal(‘0.1429’); the input Decimals remain immutable values. For the CCA fundraiser, add one near-miss that exposes changing a Context and expecting already stored coefficients to be rewritten. 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 changing a Context and expecting already stored coefficients to be rewritten.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Write the value and the active arithmetic policy in separate boxes, then run one operation that requires rounding.” 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 decimal.Context syntax. For this chapter, useful prompts are: “What did you expect from Context is the arithmetic environment?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing changing a Context and expecting already stored coefficients to be rewritten be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny library fines with daily charges, caps and a flag report for rounded results. Include one ordinary case, one boundary and one deliberate failure caused by changing a Context and expecting already stored coefficients to be rewritten. 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 Context supplies precision, rounding, exponent limits, flags and traps for Decimal operations; it is not the Decimal value itself. It shows a trace, not only a final value. The ordinary case should demonstrate “Division consults the current precision and produces Decimal(‘0.1429’); the input Decimals remain immutable values.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Write the value and the active arithmetic policy in separate boxes, then run one operation that requires rounding. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Context is the arithmetic environment, separate the documented Python decimal.Context 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. Construction and arithmetic are different stages

Back to contents

Constructing a Decimal from a valid string preserves the digits supplied even when active precision is smaller; later arithmetic applies context rules. 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 context precision as a storage limit that truncates every constructor. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Construct a long string under low precision, inspect it, then add zero and compare the results.

For the Construction and arithmetic are different stages chapter on Python decimal.Context, 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 context precision as a storage limit that truncates every constructor. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from decimal import Decimal, localcontext
with localcontext() as c:
    c.prec=3
    x=Decimal('1.23456')
    print(x,x+Decimal('0'))

Explained result. x retains 1.23456, while the arithmetic operation rounds its result to 1.23 under the three-digit context. 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: science practical. Contrast the rule using measured values with significant digits and an inexact-result audit. 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 “Constructing a Decimal from a valid string preserves the digits supplied even when active precision is smaller; later arithmetic applies context rules.” Apply this procedure: Construct a long string under low precision, inspect it, then add zero and compare the results. The expected mechanism is: x retains 1.23456, while the arithmetic operation rounds its result to 1.23 under the three-digit context. For the science practical, add one near-miss that exposes treating context precision as a storage limit that truncates every constructor. 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: CCA fundraiser. Stress-test the rule using cash totals, percentage adjustments and explicit half-up rounding. 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 “Constructing a Decimal from a valid string preserves the digits supplied even when active precision is smaller; later arithmetic applies context rules.” Apply this procedure: Construct a long string under low precision, inspect it, then add zero and compare the results. The expected mechanism is: x retains 1.23456, while the arithmetic operation rounds its result to 1.23 under the three-digit context. For the CCA fundraiser, add one near-miss that exposes treating context precision as a storage limit that truncates every constructor. 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: family planner. Explain the rule using temporary calculation policy that must not leak into later work. 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 “Constructing a Decimal from a valid string preserves the digits supplied even when active precision is smaller; later arithmetic applies context rules.” Apply this procedure: Construct a long string under low precision, inspect it, then add zero and compare the results. The expected mechanism is: x retains 1.23456, while the arithmetic operation rounds its result to 1.23 under the three-digit context. For the family planner, add one near-miss that exposes treating context precision as a storage limit that truncates every constructor. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: library fines. Transfer the rule using daily charges, caps and a flag report for rounded results. 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 “Constructing a Decimal from a valid string preserves the digits supplied even when active precision is smaller; later arithmetic applies context rules.” Apply this procedure: Construct a long string under low precision, inspect it, then add zero and compare the results. The expected mechanism is: x retains 1.23456, while the arithmetic operation rounds its result to 1.23 under the three-digit context. For the library fines, add one near-miss that exposes treating context precision as a storage limit that truncates every constructor. 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 context precision as a storage limit that truncates every constructor.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Construct a long string under low precision, inspect it, then add zero and compare the results.” 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 decimal.Context syntax. For this chapter, useful prompts are: “What did you expect from Construction and arithmetic are different stages?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing treating context precision as a storage limit that truncates every constructor 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 precision, exponent bounds, flags, traps, floats and nested local contexts. Include one ordinary case, one boundary and one deliberate failure caused by treating context precision as a storage limit that truncates every constructor. 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: Constructing a Decimal from a valid string preserves the digits supplied even when active precision is smaller; later arithmetic applies context rules. It shows a trace, not only a final value. The ordinary case should demonstrate “x retains 1.23456, while the arithmetic operation rounds its result to 1.23 under the three-digit context.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Construct a long string under low precision, inspect it, then add zero and compare the results. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Construction and arithmetic are different stages, separate the documented Python decimal.Context 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. getcontext returns the current policy

Back to contents

getcontext() returns the Context active for the current execution context, so mutating it changes subsequent context-sensitive arithmetic in that scope. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.

The high-value mistake in this chapter is calling getcontext repeatedly and assuming each result is an unrelated fresh policy. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Compare identity and one division before and after a precision change inside a disposable test.

For the getcontext returns the current policy chapter on Python decimal.Context, 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 calling getcontext repeatedly and assuming each result is an unrelated fresh policy. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from decimal import getcontext
a=getcontext(); b=getcontext()
print(a is b)
a.prec=6

Explained result. The calls refer to the active context, so the identity check is true and later arithmetic sees precision six. 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: family planner. Stress-test the rule using temporary calculation policy that must not leak into later work. 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 “getcontext() returns the Context active for the current execution context, so mutating it changes subsequent context-sensitive arithmetic in that scope.” Apply this procedure: Compare identity and one division before and after a precision change inside a disposable test. The expected mechanism is: The calls refer to the active context, so the identity check is true and later arithmetic sees precision six. For the family planner, add one near-miss that exposes calling getcontext repeatedly and assuming each result is an unrelated fresh 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: library fines. Explain the rule using daily charges, caps and a flag report for rounded results. 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 “getcontext() returns the Context active for the current execution context, so mutating it changes subsequent context-sensitive arithmetic in that scope.” Apply this procedure: Compare identity and one division before and after a precision change inside a disposable test. The expected mechanism is: The calls refer to the active context, so the identity check is true and later arithmetic sees precision six. For the library fines, add one near-miss that exposes calling getcontext repeatedly and assuming each result is an unrelated fresh 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. Transfer the rule using precision, exponent bounds, flags, traps, floats and nested local contexts. 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 “getcontext() returns the Context active for the current execution context, so mutating it changes subsequent context-sensitive arithmetic in that scope.” Apply this procedure: Compare identity and one division before and after a precision change inside a disposable test. The expected mechanism is: The calls refer to the active context, so the identity check is true and later arithmetic sees precision six. For the test laboratory, add one near-miss that exposes calling getcontext repeatedly and assuming each result is an unrelated fresh 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 decision. Predict the rule using Decimal context compared with float, Fraction and explicit quantize calls. 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 “getcontext() returns the Context active for the current execution context, so mutating it changes subsequent context-sensitive arithmetic in that scope.” Apply this procedure: Compare identity and one division before and after a precision change inside a disposable test. The expected mechanism is: The calls refer to the active context, so the identity check is true and later arithmetic sees precision six. For the design decision, add one near-miss that exposes calling getcontext repeatedly and assuming each result is an unrelated fresh 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 calling getcontext repeatedly and assuming each result is an unrelated fresh policy.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Compare identity and one division before and after a precision change inside a disposable test.” 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 decimal.Context syntax. For this chapter, useful prompts are: “What did you expect from getcontext returns the current policy?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing calling getcontext repeatedly and assuming each result is an unrelated fresh policy be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny design decision with Decimal context compared with float, Fraction and explicit quantize calls. Include one ordinary case, one boundary and one deliberate failure caused by calling getcontext repeatedly and assuming each result is an unrelated fresh 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: getcontext() returns the Context active for the current execution context, so mutating it changes subsequent context-sensitive arithmetic in that scope. It shows a trace, not only a final value. The ordinary case should demonstrate “The calls refer to the active context, so the identity check is true and later arithmetic sees precision six.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Compare identity and one division before and after a precision change inside a disposable test. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For getcontext returns the current policy, separate the documented Python decimal.Context 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. setcontext installs a chosen policy

Back to contents

setcontext() installs a copy of the supplied Context as current, useful when an application establishes one explicit arithmetic policy. 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 creating a Context object and assuming ordinary operators consult it automatically. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Build a named Context, install it at a controlled boundary and verify settings before calculating.

For the setcontext installs a chosen policy chapter on Python decimal.Context, 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 creating a Context object and assuming ordinary operators consult it automatically. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from decimal import Context, ROUND_HALF_UP, setcontext
setcontext(Context(prec=10,rounding=ROUND_HALF_UP))

Explained result. Subsequent context-sensitive arithmetic uses ten significant digits and half-up rounding in that execution context. 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 precision, exponent bounds, flags, traps, floats and nested local contexts. 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 “setcontext() installs a copy of the supplied Context as current, useful when an application establishes one explicit arithmetic policy.” Apply this procedure: Build a named Context, install it at a controlled boundary and verify settings before calculating. The expected mechanism is: Subsequent context-sensitive arithmetic uses ten significant digits and half-up rounding in that execution context. For the test laboratory, add one near-miss that exposes creating a Context object and assuming ordinary operators consult it automatically. 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 decision. Transfer the rule using Decimal context compared with float, Fraction and explicit quantize calls. 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 “setcontext() installs a copy of the supplied Context as current, useful when an application establishes one explicit arithmetic policy.” Apply this procedure: Build a named Context, install it at a controlled boundary and verify settings before calculating. The expected mechanism is: Subsequent context-sensitive arithmetic uses ten significant digits and half-up rounding in that execution context. For the design decision, add one near-miss that exposes creating a Context object and assuming ordinary operators consult it automatically. 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: canteen budget. Predict the rule using prices, quantities, discounts and a two-place reporting rule. 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 “setcontext() installs a copy of the supplied Context as current, useful when an application establishes one explicit arithmetic policy.” Apply this procedure: Build a named Context, install it at a controlled boundary and verify settings before calculating. The expected mechanism is: Subsequent context-sensitive arithmetic uses ten significant digits and half-up rounding in that execution context. For the canteen budget, add one near-miss that exposes creating a Context object and assuming ordinary operators consult it automatically. 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: reading tracker. Contrast the rule using percentage completion calculated under a stated precision. 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 “setcontext() installs a copy of the supplied Context as current, useful when an application establishes one explicit arithmetic policy.” Apply this procedure: Build a named Context, install it at a controlled boundary and verify settings before calculating. The expected mechanism is: Subsequent context-sensitive arithmetic uses ten significant digits and half-up rounding in that execution context. For the reading tracker, add one near-miss that exposes creating a Context object and assuming ordinary operators consult it automatically. 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 creating a Context object and assuming ordinary operators consult it automatically.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Build a named Context, install it at a controlled boundary and verify settings before calculating.” 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 decimal.Context syntax. For this chapter, useful prompts are: “What did you expect from setcontext installs a chosen policy?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing creating a Context object and assuming ordinary operators consult it automatically be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny canteen budget with prices, quantities, discounts and a two-place reporting rule. Include one ordinary case, one boundary and one deliberate failure caused by creating a Context object and assuming ordinary operators consult it automatically. 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: setcontext() installs a copy of the supplied Context as current, useful when an application establishes one explicit arithmetic policy. It shows a trace, not only a final value. The ordinary case should demonstrate “Subsequent context-sensitive arithmetic uses ten significant digits and half-up rounding in that execution context.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Build a named Context, install it at a controlled boundary and verify settings before calculating. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For setcontext installs a chosen policy, separate the documented Python decimal.Context 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. localcontext contains temporary changes

Back to contents

localcontext() enters a copy of a supplied or current Context and restores the previous current policy when the with block ends. 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 changing the current context for one report and leaking that policy into unrelated work. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Record precision before, inside and after the block, then rehearse the same trace with an exception.

For the localcontext contains temporary changes chapter on Python decimal.Context, 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 changing the current context for one report and leaking that policy into unrelated work. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from decimal import localcontext, getcontext
before=getcontext().prec
with localcontext() as c:
    c.prec=6
after=getcontext().prec

Explained result. The inner arithmetic sees precision six, while after equals before because context-manager unwinding restores the outer 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: canteen budget. Transfer the rule using prices, quantities, discounts and a two-place reporting rule. 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 “localcontext() enters a copy of a supplied or current Context and restores the previous current policy when the with block ends.” Apply this procedure: Record precision before, inside and after the block, then rehearse the same trace with an exception. The expected mechanism is: The inner arithmetic sees precision six, while after equals before because context-manager unwinding restores the outer policy. For the canteen budget, add one near-miss that exposes changing the current context for one report and leaking that policy into unrelated work. 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: reading tracker. Predict the rule using percentage completion calculated under a stated precision. 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 “localcontext() enters a copy of a supplied or current Context and restores the previous current policy when the with block ends.” Apply this procedure: Record precision before, inside and after the block, then rehearse the same trace with an exception. The expected mechanism is: The inner arithmetic sees precision six, while after equals before because context-manager unwinding restores the outer policy. For the reading tracker, add one near-miss that exposes changing the current context for one report and leaking that policy into unrelated work. 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: science practical. Contrast the rule using measured values with significant digits and an inexact-result audit. 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 “localcontext() enters a copy of a supplied or current Context and restores the previous current policy when the with block ends.” Apply this procedure: Record precision before, inside and after the block, then rehearse the same trace with an exception. The expected mechanism is: The inner arithmetic sees precision six, while after equals before because context-manager unwinding restores the outer policy. For the science practical, add one near-miss that exposes changing the current context for one report and leaking that policy into unrelated work. 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: CCA fundraiser. Stress-test the rule using cash totals, percentage adjustments and explicit half-up rounding. 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 “localcontext() enters a copy of a supplied or current Context and restores the previous current policy when the with block ends.” Apply this procedure: Record precision before, inside and after the block, then rehearse the same trace with an exception. The expected mechanism is: The inner arithmetic sees precision six, while after equals before because context-manager unwinding restores the outer policy. For the CCA fundraiser, add one near-miss that exposes changing the current context for one report and leaking that policy into unrelated work. 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 changing the current context for one report and leaking that policy into unrelated work.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Record precision before, inside and after the block, then rehearse the same trace with an 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 decimal.Context syntax. For this chapter, useful prompts are: “What did you expect from localcontext contains temporary changes?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing changing the current context for one report and leaking that policy into unrelated work be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny reading tracker with percentage completion calculated under a stated precision. Include one ordinary case, one boundary and one deliberate failure caused by changing the current context for one report and leaking that policy into unrelated work. 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: localcontext() enters a copy of a supplied or current Context and restores the previous current policy when the with block ends. It shows a trace, not only a final value. The ordinary case should demonstrate “The inner arithmetic sees precision six, while after equals before because context-manager unwinding restores the outer policy.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Record precision before, inside and after the block, then rehearse the same trace with an exception. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For localcontext contains temporary changes, separate the documented Python decimal.Context 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. Precision counts significant digits

Back to contents

Context.prec limits significant digits in arithmetic results, not the number of places after the decimal point. 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 setting prec=2 and calling it a cents rule. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Compare large and small magnitudes under one precision, then use quantize for a fixed-scale requirement.

For the Precision counts significant digits chapter on Python decimal.Context, 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 setting prec=2 and calling it a cents rule. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from decimal import Decimal, localcontext
with localcontext() as c:
    c.prec=3
    print(Decimal('123.4')+Decimal('0.1'))

Explained result. The result is rounded to three significant digits, 123, showing why precision alone is not a two-decimal-place 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: science practical. Predict the rule using measured values with significant digits and an inexact-result audit. 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 “Context.prec limits significant digits in arithmetic results, not the number of places after the decimal point.” Apply this procedure: Compare large and small magnitudes under one precision, then use quantize for a fixed-scale requirement. The expected mechanism is: The result is rounded to three significant digits, 123, showing why precision alone is not a two-decimal-place policy. For the science practical, add one near-miss that exposes setting prec=2 and calling it a cents rule. 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: CCA fundraiser. Contrast the rule using cash totals, percentage adjustments and explicit half-up rounding. 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 “Context.prec limits significant digits in arithmetic results, not the number of places after the decimal point.” Apply this procedure: Compare large and small magnitudes under one precision, then use quantize for a fixed-scale requirement. The expected mechanism is: The result is rounded to three significant digits, 123, showing why precision alone is not a two-decimal-place policy. For the CCA fundraiser, add one near-miss that exposes setting prec=2 and calling it a cents rule. 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: family planner. Stress-test the rule using temporary calculation policy that must not leak into later work. 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 “Context.prec limits significant digits in arithmetic results, not the number of places after the decimal point.” Apply this procedure: Compare large and small magnitudes under one precision, then use quantize for a fixed-scale requirement. The expected mechanism is: The result is rounded to three significant digits, 123, showing why precision alone is not a two-decimal-place policy. For the family planner, add one near-miss that exposes setting prec=2 and calling it a cents rule. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: library fines. Explain the rule using daily charges, caps and a flag report for rounded results. 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 “Context.prec limits significant digits in arithmetic results, not the number of places after the decimal point.” Apply this procedure: Compare large and small magnitudes under one precision, then use quantize for a fixed-scale requirement. The expected mechanism is: The result is rounded to three significant digits, 123, showing why precision alone is not a two-decimal-place policy. For the library fines, add one near-miss that exposes setting prec=2 and calling it a cents rule. 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 setting prec=2 and calling it a cents rule.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Compare large and small magnitudes under one precision, then use quantize for a fixed-scale requirement.” 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 decimal.Context syntax. For this chapter, useful prompts are: “What did you expect from Precision counts significant digits?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing setting prec=2 and calling it a cents rule be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny science practical with measured values with significant digits and an inexact-result audit. Include one ordinary case, one boundary and one deliberate failure caused by setting prec=2 and calling it a cents rule. 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: Context.prec limits significant digits in arithmetic results, not the number of places after the decimal point. It shows a trace, not only a final value. The ordinary case should demonstrate “The result is rounded to three significant digits, 123, showing why precision alone is not a two-decimal-place policy.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Compare large and small magnitudes under one precision, then use quantize for a fixed-scale requirement. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Precision counts significant digits, separate the documented Python decimal.Context 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. Rounding mode is a named policy

Back to contents

The rounding attribute selects one documented mode whenever an operation must discard digits. 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 describing all rounding as ordinary school rounding without naming tie and direction behaviour. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Use an exact tie and compare ROUND_HALF_EVEN with ROUND_HALF_UP at the same target exponent.

For the Rounding mode is a named policy chapter on Python decimal.Context, 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 describing all rounding as ordinary school rounding without naming tie and direction behaviour. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from decimal import Decimal, ROUND_HALF_EVEN, ROUND_HALF_UP
x=Decimal('2.5')
print(x.quantize(Decimal('1'),rounding=ROUND_HALF_EVEN))
print(x.quantize(Decimal('1'),rounding=ROUND_HALF_UP))

Explained result. The results are 2 and 3, proving that a tie policy is substantive input rather than decoration. 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: family planner. Contrast the rule using temporary calculation policy that must not leak into later work. 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 rounding attribute selects one documented mode whenever an operation must discard digits.” Apply this procedure: Use an exact tie and compare ROUND_HALF_EVEN with ROUND_HALF_UP at the same target exponent. The expected mechanism is: The results are 2 and 3, proving that a tie policy is substantive input rather than decoration. For the family planner, add one near-miss that exposes describing all rounding as ordinary school rounding without naming tie and direction 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: library fines. Stress-test the rule using daily charges, caps and a flag report for rounded results. 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 rounding attribute selects one documented mode whenever an operation must discard digits.” Apply this procedure: Use an exact tie and compare ROUND_HALF_EVEN with ROUND_HALF_UP at the same target exponent. The expected mechanism is: The results are 2 and 3, proving that a tie policy is substantive input rather than decoration. For the library fines, add one near-miss that exposes describing all rounding as ordinary school rounding without naming tie and direction 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: test laboratory. Explain the rule using precision, exponent bounds, flags, traps, floats and nested local contexts. 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 rounding attribute selects one documented mode whenever an operation must discard digits.” Apply this procedure: Use an exact tie and compare ROUND_HALF_EVEN with ROUND_HALF_UP at the same target exponent. The expected mechanism is: The results are 2 and 3, proving that a tie policy is substantive input rather than decoration. For the test laboratory, add one near-miss that exposes describing all rounding as ordinary school rounding without naming tie and direction 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: design decision. Transfer the rule using Decimal context compared with float, Fraction and explicit quantize calls. 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 rounding attribute selects one documented mode whenever an operation must discard digits.” Apply this procedure: Use an exact tie and compare ROUND_HALF_EVEN with ROUND_HALF_UP at the same target exponent. The expected mechanism is: The results are 2 and 3, proving that a tie policy is substantive input rather than decoration. For the design decision, add one near-miss that exposes describing all rounding as ordinary school rounding without naming tie and direction 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 describing all rounding as ordinary school rounding without naming tie and direction behaviour.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Use an exact tie and compare ROUND_HALF_EVEN with ROUND_HALF_UP at the same target exponent.” 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 decimal.Context syntax. For this chapter, useful prompts are: “What did you expect from Rounding mode is a named policy?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing describing all rounding as ordinary school rounding without naming tie and direction behaviour be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny CCA fundraiser with cash totals, percentage adjustments and explicit half-up rounding. Include one ordinary case, one boundary and one deliberate failure caused by describing all rounding as ordinary school rounding without naming tie and direction 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: The rounding attribute selects one documented mode whenever an operation must discard digits. It shows a trace, not only a final value. The ordinary case should demonstrate “The results are 2 and 3, proving that a tie policy is substantive input rather than decoration.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Use an exact tie and compare ROUND_HALF_EVEN with ROUND_HALF_UP at the same target exponent. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Rounding mode is a named policy, separate the documented Python decimal.Context 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. quantize expresses a fixed exponent

Back to contents

quantize() rounds to the exponent of another Decimal and can take an explicit rounding rule, directly expressing a scale such as cents. 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 context precision as a substitute for a fixed two-place output rule. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Choose the target exponent explicitly and test positive, negative and halfway values.

For the quantize expresses a fixed exponent chapter on Python decimal.Context, 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 context precision as a substitute for a fixed two-place output rule. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from decimal import Decimal, ROUND_HALF_UP
print(Decimal('7.325').quantize(Decimal('0.01'),rounding=ROUND_HALF_UP))

Explained result. The target exponent is hundredths and half-up produces Decimal(‘7.33’). 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 precision, exponent bounds, flags, traps, floats and nested local contexts. 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 “quantize() rounds to the exponent of another Decimal and can take an explicit rounding rule, directly expressing a scale such as cents.” Apply this procedure: Choose the target exponent explicitly and test positive, negative and halfway values. The expected mechanism is: The target exponent is hundredths and half-up produces Decimal(‘7.33’). For the test laboratory, add one near-miss that exposes using context precision as a substitute for a fixed two-place output rule. 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 decision. Explain the rule using Decimal context compared with float, Fraction and explicit quantize calls. 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 “quantize() rounds to the exponent of another Decimal and can take an explicit rounding rule, directly expressing a scale such as cents.” Apply this procedure: Choose the target exponent explicitly and test positive, negative and halfway values. The expected mechanism is: The target exponent is hundredths and half-up produces Decimal(‘7.33’). For the design decision, add one near-miss that exposes using context precision as a substitute for a fixed two-place output rule. 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: canteen budget. Transfer the rule using prices, quantities, discounts and a two-place reporting rule. 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 “quantize() rounds to the exponent of another Decimal and can take an explicit rounding rule, directly expressing a scale such as cents.” Apply this procedure: Choose the target exponent explicitly and test positive, negative and halfway values. The expected mechanism is: The target exponent is hundredths and half-up produces Decimal(‘7.33’). For the canteen budget, add one near-miss that exposes using context precision as a substitute for a fixed two-place output rule. 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: reading tracker. Predict the rule using percentage completion calculated under a stated precision. 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 “quantize() rounds to the exponent of another Decimal and can take an explicit rounding rule, directly expressing a scale such as cents.” Apply this procedure: Choose the target exponent explicitly and test positive, negative and halfway values. The expected mechanism is: The target exponent is hundredths and half-up produces Decimal(‘7.33’). For the reading tracker, add one near-miss that exposes using context precision as a substitute for a fixed two-place output rule. 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 context precision as a substitute for a fixed two-place output rule.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Choose the target exponent explicitly and test positive, negative and halfway values.” 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 decimal.Context syntax. For this chapter, useful prompts are: “What did you expect from quantize expresses a fixed exponent?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing using context precision as a substitute for a fixed two-place output rule be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny family planner with temporary calculation policy that must not leak into later work. Include one ordinary case, one boundary and one deliberate failure caused by using context precision as a substitute for a fixed two-place output rule. 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: quantize() rounds to the exponent of another Decimal and can take an explicit rounding rule, directly expressing a scale such as cents. It shows a trace, not only a final value. The ordinary case should demonstrate “The target exponent is hundredths and half-up produces Decimal(‘7.33’).” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Choose the target exponent explicitly and test positive, negative and halfway values. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For quantize expresses a fixed exponent, separate the documented Python decimal.Context 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. Emin and Emax bound adjusted exponents

Back to contents

Context exponent limits define the normal operating range and interact with overflow, underflow, subnormal and clamped conditions. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.

The high-value mistake in this chapter is reading Emax as the largest coefficient or maximum count of stored digits. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Use a tiny disposable Context with small bounds and observe values near both limits.

For the Emin and Emax bound adjusted exponents chapter on Python decimal.Context, 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 reading Emax as the largest coefficient or maximum count of stored digits. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from decimal import Context, Decimal
c=Context(prec=3,Emin=-2,Emax=2)
print(c.multiply(Decimal('9.99E+2'),Decimal('1')))

Explained result. The context method applies its own precision and range, making boundary signals observable without changing the current context. 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: canteen budget. Explain the rule using prices, quantities, discounts and a two-place reporting rule. 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 “Context exponent limits define the normal operating range and interact with overflow, underflow, subnormal and clamped conditions.” Apply this procedure: Use a tiny disposable Context with small bounds and observe values near both limits. The expected mechanism is: The context method applies its own precision and range, making boundary signals observable without changing the current context. For the canteen budget, add one near-miss that exposes reading Emax as the largest coefficient or maximum count of stored digits. 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: reading tracker. Transfer the rule using percentage completion calculated under a stated precision. 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 “Context exponent limits define the normal operating range and interact with overflow, underflow, subnormal and clamped conditions.” Apply this procedure: Use a tiny disposable Context with small bounds and observe values near both limits. The expected mechanism is: The context method applies its own precision and range, making boundary signals observable without changing the current context. For the reading tracker, add one near-miss that exposes reading Emax as the largest coefficient or maximum count of stored digits. 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: science practical. Predict the rule using measured values with significant digits and an inexact-result audit. 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 “Context exponent limits define the normal operating range and interact with overflow, underflow, subnormal and clamped conditions.” Apply this procedure: Use a tiny disposable Context with small bounds and observe values near both limits. The expected mechanism is: The context method applies its own precision and range, making boundary signals observable without changing the current context. For the science practical, add one near-miss that exposes reading Emax as the largest coefficient or maximum count of stored digits. 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: CCA fundraiser. Contrast the rule using cash totals, percentage adjustments and explicit half-up rounding. 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 “Context exponent limits define the normal operating range and interact with overflow, underflow, subnormal and clamped conditions.” Apply this procedure: Use a tiny disposable Context with small bounds and observe values near both limits. The expected mechanism is: The context method applies its own precision and range, making boundary signals observable without changing the current context. For the CCA fundraiser, add one near-miss that exposes reading Emax as the largest coefficient or maximum count of stored digits. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Diagnostic route

  • Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
  • Boundary check: create the smallest input that triggers reading Emax as the largest coefficient or maximum count of stored digits.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Use a tiny disposable Context with small bounds and observe values near both limits.” 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 decimal.Context syntax. For this chapter, useful prompts are: “What did you expect from Emin and Emax bound adjusted exponents?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing reading Emax as the largest coefficient or maximum count of stored digits be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny library fines with daily charges, caps and a flag report for rounded results. Include one ordinary case, one boundary and one deliberate failure caused by reading Emax as the largest coefficient or maximum count of stored digits. 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: Context exponent limits define the normal operating range and interact with overflow, underflow, subnormal and clamped conditions. It shows a trace, not only a final value. The ordinary case should demonstrate “The context method applies its own precision and range, making boundary signals observable without changing the current context.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Use a tiny disposable Context with small bounds and observe values near both limits. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Emin and Emax bound adjusted exponents, separate the documented Python decimal.Context 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. Flags are sticky evidence

Back to contents

When a signal occurs its flag becomes true and stays true until cleared, allowing a calculation block to be audited after it runs. 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 checking a flag after several unrelated jobs and attributing it to only the last operation. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Clear flags immediately before the monitored block and inspect them immediately after it.

For the Flags are sticky evidence chapter on Python decimal.Context, 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 checking a flag after several unrelated jobs and attributing it to only the last operation. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from decimal import Decimal, getcontext
c=getcontext(); c.clear_flags()
Decimal(1)/Decimal(7)
print({s.__name__:v for s,v in c.flags.items() if v})

Explained result. Rounded and Inexact are recorded for the repeating division, and remain recorded until explicitly cleared. 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: science practical. Transfer the rule using measured values with significant digits and an inexact-result audit. 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 “When a signal occurs its flag becomes true and stays true until cleared, allowing a calculation block to be audited after it runs.” Apply this procedure: Clear flags immediately before the monitored block and inspect them immediately after it. The expected mechanism is: Rounded and Inexact are recorded for the repeating division, and remain recorded until explicitly cleared. For the science practical, add one near-miss that exposes checking a flag after several unrelated jobs and attributing it to only the last operation. 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: CCA fundraiser. Predict the rule using cash totals, percentage adjustments and explicit half-up rounding. 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 “When a signal occurs its flag becomes true and stays true until cleared, allowing a calculation block to be audited after it runs.” Apply this procedure: Clear flags immediately before the monitored block and inspect them immediately after it. The expected mechanism is: Rounded and Inexact are recorded for the repeating division, and remain recorded until explicitly cleared. For the CCA fundraiser, add one near-miss that exposes checking a flag after several unrelated jobs and attributing it to only the last operation. 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: family planner. Contrast the rule using temporary calculation policy that must not leak into later work. 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 “When a signal occurs its flag becomes true and stays true until cleared, allowing a calculation block to be audited after it runs.” Apply this procedure: Clear flags immediately before the monitored block and inspect them immediately after it. The expected mechanism is: Rounded and Inexact are recorded for the repeating division, and remain recorded until explicitly cleared. For the family planner, add one near-miss that exposes checking a flag after several unrelated jobs and attributing it to only the last operation. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: library fines. Stress-test the rule using daily charges, caps and a flag report for rounded results. 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 “When a signal occurs its flag becomes true and stays true until cleared, allowing a calculation block to be audited after it runs.” Apply this procedure: Clear flags immediately before the monitored block and inspect them immediately after it. The expected mechanism is: Rounded and Inexact are recorded for the repeating division, and remain recorded until explicitly cleared. For the library fines, add one near-miss that exposes checking a flag after several unrelated jobs and attributing it to only the last operation. 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 checking a flag after several unrelated jobs and attributing it to only the last operation.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Clear flags immediately before the monitored block and inspect them immediately after it.” 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 decimal.Context syntax. For this chapter, useful prompts are: “What did you expect from Flags are sticky evidence?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing checking a flag after several unrelated jobs and attributing it to only the last operation 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 precision, exponent bounds, flags, traps, floats and nested local contexts. Include one ordinary case, one boundary and one deliberate failure caused by checking a flag after several unrelated jobs and attributing it to only the last operation. 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: When a signal occurs its flag becomes true and stays true until cleared, allowing a calculation block to be audited after it runs. It shows a trace, not only a final value. The ordinary case should demonstrate “Rounded and Inexact are recorded for the repeating division, and remain recorded until explicitly cleared.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Clear flags immediately before the monitored block and inspect them immediately after it. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Flags are sticky evidence, separate the documented Python decimal.Context 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. Rounded and Inexact are distinct

Back to contents

Rounded means digits were discarded, whereas Inexact means at least one discarded digit was non-zero; representation can be rounded without changing numerical value. 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 every Rounded flag as proof the numerical value changed. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Compare a result that discards only zeros with one that discards non-zero digits and inspect both flags.

For the Rounded and Inexact are distinct chapter on Python decimal.Context, 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 every Rounded flag as proof the numerical value changed. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from decimal import Decimal, localcontext, Rounded, Inexact
with localcontext() as c:
    c.prec=3; c.clear_flags()
    y=Decimal('5.00')/Decimal('1')
    print(y,c.flags[Rounded],c.flags[Inexact])

Explained result. The trace separates a representation event from loss of numerical information instead of using one vague rounded label. 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: family planner. Predict the rule using temporary calculation policy that must not leak into later work. 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 “Rounded means digits were discarded, whereas Inexact means at least one discarded digit was non-zero; representation can be rounded without changing numerical value.” Apply this procedure: Compare a result that discards only zeros with one that discards non-zero digits and inspect both flags. The expected mechanism is: The trace separates a representation event from loss of numerical information instead of using one vague rounded label. For the family planner, add one near-miss that exposes treating every Rounded flag as proof the numerical value changed. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: library fines. Contrast the rule using daily charges, caps and a flag report for rounded results. 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 “Rounded means digits were discarded, whereas Inexact means at least one discarded digit was non-zero; representation can be rounded without changing numerical value.” Apply this procedure: Compare a result that discards only zeros with one that discards non-zero digits and inspect both flags. The expected mechanism is: The trace separates a representation event from loss of numerical information instead of using one vague rounded label. For the library fines, add one near-miss that exposes treating every Rounded flag as proof the numerical value changed. 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 precision, exponent bounds, flags, traps, floats and nested local contexts. 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 “Rounded means digits were discarded, whereas Inexact means at least one discarded digit was non-zero; representation can be rounded without changing numerical value.” Apply this procedure: Compare a result that discards only zeros with one that discards non-zero digits and inspect both flags. The expected mechanism is: The trace separates a representation event from loss of numerical information instead of using one vague rounded label. For the test laboratory, add one near-miss that exposes treating every Rounded flag as proof the numerical value changed. 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 decision. Explain the rule using Decimal context compared with float, Fraction and explicit quantize calls. 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 “Rounded means digits were discarded, whereas Inexact means at least one discarded digit was non-zero; representation can be rounded without changing numerical value.” Apply this procedure: Compare a result that discards only zeros with one that discards non-zero digits and inspect both flags. The expected mechanism is: The trace separates a representation event from loss of numerical information instead of using one vague rounded label. For the design decision, add one near-miss that exposes treating every Rounded flag as proof the numerical value changed. 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 every Rounded flag as proof the numerical value changed.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Compare a result that discards only zeros with one that discards non-zero digits and inspect both flags.” 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 decimal.Context syntax. For this chapter, useful prompts are: “What did you expect from Rounded and Inexact are distinct?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing treating every Rounded flag as proof the numerical value changed be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny design decision with Decimal context compared with float, Fraction and explicit quantize calls. Include one ordinary case, one boundary and one deliberate failure caused by treating every Rounded flag as proof the numerical value changed. 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: Rounded means digits were discarded, whereas Inexact means at least one discarded digit was non-zero; representation can be rounded without changing numerical value. It shows a trace, not only a final value. The ordinary case should demonstrate “The trace separates a representation event from loss of numerical information instead of using one vague rounded label.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Compare a result that discards only zeros with one that discards non-zero digits and inspect both flags. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Rounded and Inexact are distinct, separate the documented Python decimal.Context 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. Traps turn selected signals into exceptions

Back to contents

A true trap enabler raises the corresponding signal after its flag is set, making unacceptable approximation fail at the boundary. 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 enabling every trap without deciding which conditions the application can legitimately handle. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Name each forbidden condition, enable only that trap and test the smallest triggering operation.

For the Traps turn selected signals into exceptions chapter on Python decimal.Context, 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 enabling every trap without deciding which conditions the application can legitimately handle. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from decimal import Decimal, localcontext, Inexact
with localcontext() as c:
    c.traps[Inexact]=True
    print(Decimal(1)/Decimal(8))

Explained result. One eighth is exact in decimal and succeeds; replacing 8 with 7 raises Inexact under the same 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: test laboratory. Contrast the rule using precision, exponent bounds, flags, traps, floats and nested local contexts. 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 true trap enabler raises the corresponding signal after its flag is set, making unacceptable approximation fail at the boundary.” Apply this procedure: Name each forbidden condition, enable only that trap and test the smallest triggering operation. The expected mechanism is: One eighth is exact in decimal and succeeds; replacing 8 with 7 raises Inexact under the same policy. For the test laboratory, add one near-miss that exposes enabling every trap without deciding which conditions the application can legitimately handle. 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 decision. Stress-test the rule using Decimal context compared with float, Fraction and explicit quantize calls. 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 true trap enabler raises the corresponding signal after its flag is set, making unacceptable approximation fail at the boundary.” Apply this procedure: Name each forbidden condition, enable only that trap and test the smallest triggering operation. The expected mechanism is: One eighth is exact in decimal and succeeds; replacing 8 with 7 raises Inexact under the same policy. For the design decision, add one near-miss that exposes enabling every trap without deciding which conditions the application can legitimately handle. 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: canteen budget. Explain the rule using prices, quantities, discounts and a two-place reporting rule. 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 true trap enabler raises the corresponding signal after its flag is set, making unacceptable approximation fail at the boundary.” Apply this procedure: Name each forbidden condition, enable only that trap and test the smallest triggering operation. The expected mechanism is: One eighth is exact in decimal and succeeds; replacing 8 with 7 raises Inexact under the same policy. For the canteen budget, add one near-miss that exposes enabling every trap without deciding which conditions the application can legitimately handle. 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: reading tracker. Transfer the rule using percentage completion calculated under a stated precision. 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 true trap enabler raises the corresponding signal after its flag is set, making unacceptable approximation fail at the boundary.” Apply this procedure: Name each forbidden condition, enable only that trap and test the smallest triggering operation. The expected mechanism is: One eighth is exact in decimal and succeeds; replacing 8 with 7 raises Inexact under the same policy. For the reading tracker, add one near-miss that exposes enabling every trap without deciding which conditions the application can legitimately handle. 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 enabling every trap without deciding which conditions the application can legitimately handle.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Name each forbidden condition, enable only that trap and test the smallest triggering operation.” 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 decimal.Context syntax. For this chapter, useful prompts are: “What did you expect from Traps turn selected signals into exceptions?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing enabling every trap without deciding which conditions the application can legitimately handle be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny canteen budget with prices, quantities, discounts and a two-place reporting rule. Include one ordinary case, one boundary and one deliberate failure caused by enabling every trap without deciding which conditions the application can legitimately handle. 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 true trap enabler raises the corresponding signal after its flag is set, making unacceptable approximation fail at the boundary. It shows a trace, not only a final value. The ordinary case should demonstrate “One eighth is exact in decimal and succeeds; replacing 8 with 7 raises Inexact under the same policy.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Name each forbidden condition, enable only that trap and test the smallest triggering operation. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Traps turn selected signals into exceptions, separate the documented Python decimal.Context 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. DivisionByZero can be trapped or represented

Back to contents

With its trap disabled, DivisionByZero can return an infinity and set a flag; with the trap enabled it raises an exception. 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 Decimal division always behaves like integer division or always returns Infinity. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Run the same operation under copied contexts with the trap disabled and enabled.

For the DivisionByZero can be trapped or represented chapter on Python decimal.Context, 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 Decimal division always behaves like integer division or always returns Infinity. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from decimal import Context, Decimal, DivisionByZero
c=Context(); c.traps[DivisionByZero]=False
print(c.divide(Decimal(1),Decimal(0)),c.flags[DivisionByZero])

Explained result. The explicit Context returns Infinity and records the condition because its DivisionByZero trap is disabled. 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: canteen budget. Stress-test the rule using prices, quantities, discounts and a two-place reporting rule. 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 “With its trap disabled, DivisionByZero can return an infinity and set a flag; with the trap enabled it raises an exception.” Apply this procedure: Run the same operation under copied contexts with the trap disabled and enabled. The expected mechanism is: The explicit Context returns Infinity and records the condition because its DivisionByZero trap is disabled. For the canteen budget, add one near-miss that exposes assuming Decimal division always behaves like integer division or always returns Infinity. 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: reading tracker. Explain the rule using percentage completion calculated under a stated precision. 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 “With its trap disabled, DivisionByZero can return an infinity and set a flag; with the trap enabled it raises an exception.” Apply this procedure: Run the same operation under copied contexts with the trap disabled and enabled. The expected mechanism is: The explicit Context returns Infinity and records the condition because its DivisionByZero trap is disabled. For the reading tracker, add one near-miss that exposes assuming Decimal division always behaves like integer division or always returns Infinity. 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: science practical. Transfer the rule using measured values with significant digits and an inexact-result audit. 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 “With its trap disabled, DivisionByZero can return an infinity and set a flag; with the trap enabled it raises an exception.” Apply this procedure: Run the same operation under copied contexts with the trap disabled and enabled. The expected mechanism is: The explicit Context returns Infinity and records the condition because its DivisionByZero trap is disabled. For the science practical, add one near-miss that exposes assuming Decimal division always behaves like integer division or always returns Infinity. 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: CCA fundraiser. Predict the rule using cash totals, percentage adjustments and explicit half-up rounding. 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 “With its trap disabled, DivisionByZero can return an infinity and set a flag; with the trap enabled it raises an exception.” Apply this procedure: Run the same operation under copied contexts with the trap disabled and enabled. The expected mechanism is: The explicit Context returns Infinity and records the condition because its DivisionByZero trap is disabled. For the CCA fundraiser, add one near-miss that exposes assuming Decimal division always behaves like integer division or always returns Infinity. 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 Decimal division always behaves like integer division or always returns Infinity.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Run the same operation under copied contexts with the trap disabled and enabled.” 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 decimal.Context syntax. For this chapter, useful prompts are: “What did you expect from DivisionByZero can be trapped or represented?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing assuming Decimal division always behaves like integer division or always returns Infinity be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny reading tracker with percentage completion calculated under a stated precision. Include one ordinary case, one boundary and one deliberate failure caused by assuming Decimal division always behaves like integer division or always returns Infinity. 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: With its trap disabled, DivisionByZero can return an infinity and set a flag; with the trap enabled it raises an exception. It shows a trace, not only a final value. The ordinary case should demonstrate “The explicit Context returns Infinity and records the condition because its DivisionByZero trap is disabled.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Run the same operation under copied contexts with the trap disabled and enabled. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For DivisionByZero can be trapped or represented, separate the documented Python decimal.Context 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. FloatOperation exposes accidental binary input

Back to contents

FloatOperation can record or trap mixed use of binary floats in Decimal construction and selected comparisons, protecting a decimal-only boundary. 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 writing Decimal(0.1) and believing it denotes the exact decimal tenth. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Contrast construction from a string with construction from a float while the trap is enabled.

For the FloatOperation exposes accidental binary input chapter on Python decimal.Context, 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 writing Decimal(0.1) and believing it denotes the exact decimal tenth. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from decimal import Decimal, localcontext, FloatOperation
with localcontext() as c:
    c.traps[FloatOperation]=True
    Decimal(0.1)

Explained result. The constructor raises FloatOperation, directing callers to Decimal(‘0.1’) when an exact decimal tenth is intended. 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: science practical. Explain the rule using measured values with significant digits and an inexact-result audit. 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 “FloatOperation can record or trap mixed use of binary floats in Decimal construction and selected comparisons, protecting a decimal-only boundary.” Apply this procedure: Contrast construction from a string with construction from a float while the trap is enabled. The expected mechanism is: The constructor raises FloatOperation, directing callers to Decimal(‘0.1’) when an exact decimal tenth is intended. For the science practical, add one near-miss that exposes writing Decimal(0.1) and believing it denotes the exact decimal tenth. 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: CCA fundraiser. Transfer the rule using cash totals, percentage adjustments and explicit half-up rounding. 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 “FloatOperation can record or trap mixed use of binary floats in Decimal construction and selected comparisons, protecting a decimal-only boundary.” Apply this procedure: Contrast construction from a string with construction from a float while the trap is enabled. The expected mechanism is: The constructor raises FloatOperation, directing callers to Decimal(‘0.1’) when an exact decimal tenth is intended. For the CCA fundraiser, add one near-miss that exposes writing Decimal(0.1) and believing it denotes the exact decimal tenth. 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: family planner. Predict the rule using temporary calculation policy that must not leak into later work. 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 “FloatOperation can record or trap mixed use of binary floats in Decimal construction and selected comparisons, protecting a decimal-only boundary.” Apply this procedure: Contrast construction from a string with construction from a float while the trap is enabled. The expected mechanism is: The constructor raises FloatOperation, directing callers to Decimal(‘0.1’) when an exact decimal tenth is intended. For the family planner, add one near-miss that exposes writing Decimal(0.1) and believing it denotes the exact decimal tenth. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: library fines. Contrast the rule using daily charges, caps and a flag report for rounded results. 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 “FloatOperation can record or trap mixed use of binary floats in Decimal construction and selected comparisons, protecting a decimal-only boundary.” Apply this procedure: Contrast construction from a string with construction from a float while the trap is enabled. The expected mechanism is: The constructor raises FloatOperation, directing callers to Decimal(‘0.1’) when an exact decimal tenth is intended. For the library fines, add one near-miss that exposes writing Decimal(0.1) and believing it denotes the exact decimal tenth. 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 writing Decimal(0.1) and believing it denotes the exact decimal tenth.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Contrast construction from a string with construction from a float while the trap is enabled.” 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 decimal.Context syntax. For this chapter, useful prompts are: “What did you expect from FloatOperation exposes accidental binary input?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing writing Decimal(0.1) and believing it denotes the exact decimal tenth be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny science practical with measured values with significant digits and an inexact-result audit. Include one ordinary case, one boundary and one deliberate failure caused by writing Decimal(0.1) and believing it denotes the exact decimal tenth. 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: FloatOperation can record or trap mixed use of binary floats in Decimal construction and selected comparisons, protecting a decimal-only boundary. It shows a trace, not only a final value. The ordinary case should demonstrate “The constructor raises FloatOperation, directing callers to Decimal(‘0.1’) when an exact decimal tenth is intended.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Contrast construction from a string with construction from a float while the trap is enabled. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For FloatOperation exposes accidental binary input, separate the documented Python decimal.Context 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. Context methods make policy explicit

Back to contents

A Context exposes arithmetic methods such as add, divide and quantize that apply that particular policy even when it is not current. 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 creating a Context but using ordinary operators and assuming that object is consulted. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Compare c.divide(x,y) with x/y while a different current context is active.

For the Context methods make policy explicit chapter on Python decimal.Context, 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 creating a Context but using ordinary operators and assuming that object is consulted. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from decimal import Context, Decimal
c=Context(prec=5)
print(c.divide(Decimal(1),Decimal(7)))

Explained result. The method produces a five-significant-digit result under c without first installing c as current. 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: family planner. Transfer the rule using temporary calculation policy that must not leak into later work. 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 Context exposes arithmetic methods such as add, divide and quantize that apply that particular policy even when it is not current.” Apply this procedure: Compare c.divide(x,y) with x/y while a different current context is active. The expected mechanism is: The method produces a five-significant-digit result under c without first installing c as current. For the family planner, add one near-miss that exposes creating a Context but using ordinary operators and assuming that object is consulted. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: library fines. Predict the rule using daily charges, caps and a flag report for rounded results. 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 Context exposes arithmetic methods such as add, divide and quantize that apply that particular policy even when it is not current.” Apply this procedure: Compare c.divide(x,y) with x/y while a different current context is active. The expected mechanism is: The method produces a five-significant-digit result under c without first installing c as current. For the library fines, add one near-miss that exposes creating a Context but using ordinary operators and assuming that object is consulted. 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 precision, exponent bounds, flags, traps, floats and nested local contexts. 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 Context exposes arithmetic methods such as add, divide and quantize that apply that particular policy even when it is not current.” Apply this procedure: Compare c.divide(x,y) with x/y while a different current context is active. The expected mechanism is: The method produces a five-significant-digit result under c without first installing c as current. For the test laboratory, add one near-miss that exposes creating a Context but using ordinary operators and assuming that object is consulted. 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 decision. Stress-test the rule using Decimal context compared with float, Fraction and explicit quantize calls. 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 Context exposes arithmetic methods such as add, divide and quantize that apply that particular policy even when it is not current.” Apply this procedure: Compare c.divide(x,y) with x/y while a different current context is active. The expected mechanism is: The method produces a five-significant-digit result under c without first installing c as current. For the design decision, add one near-miss that exposes creating a Context but using ordinary operators and assuming that object is consulted. 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 creating a Context but using ordinary operators and assuming that object is consulted.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Compare c.divide(x,y) with x/y while a different current context is active.” 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 decimal.Context syntax. For this chapter, useful prompts are: “What did you expect from Context methods make policy explicit?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing creating a Context but using ordinary operators and assuming that object is consulted be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny CCA fundraiser with cash totals, percentage adjustments and explicit half-up rounding. Include one ordinary case, one boundary and one deliberate failure caused by creating a Context but using ordinary operators and assuming that object is consulted. 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 Context exposes arithmetic methods such as add, divide and quantize that apply that particular policy even when it is not current. It shows a trace, not only a final value. The ordinary case should demonstrate “The method produces a five-significant-digit result under c without first installing c as current.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Compare c.divide(x,y) with x/y while a different current context is active. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Context methods make policy explicit, separate the documented Python decimal.Context 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. copy separates later mutations

Back to contents

Context.copy() creates a distinct Context with the same settings and current status at that moment, allowing a derived policy to change independently. 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 assigning a second variable to one Context and believing it is a snapshot. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Compare identity, change precision on the copy and inspect both objects.

For the copy separates later mutations chapter on Python decimal.Context, 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 assigning a second variable to one Context and believing it is a snapshot. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from decimal import getcontext
base=getcontext(); trial=base.copy()
trial.prec=12
print(base.prec,trial.prec)

Explained result. The copied policy can move to precision twelve without changing base precision. 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 precision, exponent bounds, flags, traps, floats and nested local contexts. 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 “Context.copy() creates a distinct Context with the same settings and current status at that moment, allowing a derived policy to change independently.” Apply this procedure: Compare identity, change precision on the copy and inspect both objects. The expected mechanism is: The copied policy can move to precision twelve without changing base precision. For the test laboratory, add one near-miss that exposes assigning a second variable to one Context and believing it is a snapshot. 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 decision. Contrast the rule using Decimal context compared with float, Fraction and explicit quantize calls. 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 “Context.copy() creates a distinct Context with the same settings and current status at that moment, allowing a derived policy to change independently.” Apply this procedure: Compare identity, change precision on the copy and inspect both objects. The expected mechanism is: The copied policy can move to precision twelve without changing base precision. For the design decision, add one near-miss that exposes assigning a second variable to one Context and believing it is a snapshot. 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: canteen budget. Stress-test the rule using prices, quantities, discounts and a two-place reporting rule. 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 “Context.copy() creates a distinct Context with the same settings and current status at that moment, allowing a derived policy to change independently.” Apply this procedure: Compare identity, change precision on the copy and inspect both objects. The expected mechanism is: The copied policy can move to precision twelve without changing base precision. For the canteen budget, add one near-miss that exposes assigning a second variable to one Context and believing it is a snapshot. 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: reading tracker. Explain the rule using percentage completion calculated under a stated precision. 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 “Context.copy() creates a distinct Context with the same settings and current status at that moment, allowing a derived policy to change independently.” Apply this procedure: Compare identity, change precision on the copy and inspect both objects. The expected mechanism is: The copied policy can move to precision twelve without changing base precision. For the reading tracker, add one near-miss that exposes assigning a second variable to one Context and believing it is a snapshot. 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 assigning a second variable to one Context and believing it is a snapshot.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Compare identity, change precision on the copy and inspect both objects.” 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 decimal.Context syntax. For this chapter, useful prompts are: “What did you expect from copy separates later mutations?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing assigning a second variable to one Context and believing it is a snapshot be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny family planner with temporary calculation policy that must not leak into later work. Include one ordinary case, one boundary and one deliberate failure caused by assigning a second variable to one Context and believing it is a snapshot. 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: Context.copy() creates a distinct Context with the same settings and current status at that moment, allowing a derived policy to change independently. It shows a trace, not only a final value. The ordinary case should demonstrate “The copied policy can move to precision twelve without changing base precision.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Compare identity, change precision on the copy and inspect both objects. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For copy separates later mutations, separate the documented Python decimal.Context 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. BasicContext and ExtendedContext are presets

Back to contents

The module provides standard Context presets with different trap profiles; BasicContext is especially useful when debugging because many traps are enabled. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.

The high-value mistake in this chapter is mutating a shared preset directly and turning a teaching baseline into hidden project state. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Copy the preset before customization and print its trap profile rather than trusting a slogan.

For the BasicContext and ExtendedContext are presets chapter on Python decimal.Context, 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 mutating a shared preset directly and turning a teaching baseline into hidden project state. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from decimal import BasicContext, ExtendedContext
debug=BasicContext.copy()
permissive=ExtendedContext.copy()

Explained result. The copies start from documented profiles while keeping project-specific mutations separate. 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: canteen budget. Contrast the rule using prices, quantities, discounts and a two-place reporting rule. 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 module provides standard Context presets with different trap profiles; BasicContext is especially useful when debugging because many traps are enabled.” Apply this procedure: Copy the preset before customization and print its trap profile rather than trusting a slogan. The expected mechanism is: The copies start from documented profiles while keeping project-specific mutations separate. For the canteen budget, add one near-miss that exposes mutating a shared preset directly and turning a teaching baseline into hidden project state. 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: reading tracker. Stress-test the rule using percentage completion calculated under a stated precision. 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 module provides standard Context presets with different trap profiles; BasicContext is especially useful when debugging because many traps are enabled.” Apply this procedure: Copy the preset before customization and print its trap profile rather than trusting a slogan. The expected mechanism is: The copies start from documented profiles while keeping project-specific mutations separate. For the reading tracker, add one near-miss that exposes mutating a shared preset directly and turning a teaching baseline into hidden project state. 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: science practical. Explain the rule using measured values with significant digits and an inexact-result audit. 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 module provides standard Context presets with different trap profiles; BasicContext is especially useful when debugging because many traps are enabled.” Apply this procedure: Copy the preset before customization and print its trap profile rather than trusting a slogan. The expected mechanism is: The copies start from documented profiles while keeping project-specific mutations separate. For the science practical, add one near-miss that exposes mutating a shared preset directly and turning a teaching baseline into hidden project state. 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: CCA fundraiser. Transfer the rule using cash totals, percentage adjustments and explicit half-up rounding. 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 module provides standard Context presets with different trap profiles; BasicContext is especially useful when debugging because many traps are enabled.” Apply this procedure: Copy the preset before customization and print its trap profile rather than trusting a slogan. The expected mechanism is: The copies start from documented profiles while keeping project-specific mutations separate. For the CCA fundraiser, add one near-miss that exposes mutating a shared preset directly and turning a teaching baseline into hidden project state. 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 mutating a shared preset directly and turning a teaching baseline into hidden project state.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Copy the preset before customization and print its trap profile rather than trusting a slogan.” 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 decimal.Context syntax. For this chapter, useful prompts are: “What did you expect from BasicContext and ExtendedContext are presets?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing mutating a shared preset directly and turning a teaching baseline into hidden project state be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny library fines with daily charges, caps and a flag report for rounded results. Include one ordinary case, one boundary and one deliberate failure caused by mutating a shared preset directly and turning a teaching baseline into hidden project state. 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 module provides standard Context presets with different trap profiles; BasicContext is especially useful when debugging because many traps are enabled. It shows a trace, not only a final value. The ordinary case should demonstrate “The copies start from documented profiles while keeping project-specific mutations separate.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Copy the preset before customization and print its trap profile rather than trusting a slogan. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For BasicContext and ExtendedContext are presets, separate the documented Python decimal.Context 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. Nested local contexts restore in stack order

Back to contents

Each localcontext block copies the policy visible at entry, so nested temporary changes unwind last in, first out. 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 an inner block restores the application default rather than its immediate outer policy. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Trace precision before the outer block, inside both blocks, after the inner block and after the outer block.

For the Nested local contexts restore in stack order chapter on Python decimal.Context, 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 an inner block restores the application default rather than its immediate outer policy. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from decimal import localcontext, getcontext
with localcontext() as outer:
    outer.prec=10
    with localcontext() as inner:
        inner.prec=4
    print(getcontext().prec)

Explained result. After the inner block precision is ten from the outer local Context; leaving the outer block restores the earlier 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: science practical. Stress-test the rule using measured values with significant digits and an inexact-result audit. 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 “Each localcontext block copies the policy visible at entry, so nested temporary changes unwind last in, first out.” Apply this procedure: Trace precision before the outer block, inside both blocks, after the inner block and after the outer block. The expected mechanism is: After the inner block precision is ten from the outer local Context; leaving the outer block restores the earlier policy. For the science practical, add one near-miss that exposes assuming an inner block restores the application default rather than its immediate outer 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: CCA fundraiser. Explain the rule using cash totals, percentage adjustments and explicit half-up rounding. 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 “Each localcontext block copies the policy visible at entry, so nested temporary changes unwind last in, first out.” Apply this procedure: Trace precision before the outer block, inside both blocks, after the inner block and after the outer block. The expected mechanism is: After the inner block precision is ten from the outer local Context; leaving the outer block restores the earlier policy. For the CCA fundraiser, add one near-miss that exposes assuming an inner block restores the application default rather than its immediate outer 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: family planner. Transfer the rule using temporary calculation policy that must not leak into later work. 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 “Each localcontext block copies the policy visible at entry, so nested temporary changes unwind last in, first out.” Apply this procedure: Trace precision before the outer block, inside both blocks, after the inner block and after the outer block. The expected mechanism is: After the inner block precision is ten from the outer local Context; leaving the outer block restores the earlier policy. For the family planner, add one near-miss that exposes assuming an inner block restores the application default rather than its immediate outer 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: library fines. Predict the rule using daily charges, caps and a flag report for rounded results. 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 “Each localcontext block copies the policy visible at entry, so nested temporary changes unwind last in, first out.” Apply this procedure: Trace precision before the outer block, inside both blocks, after the inner block and after the outer block. The expected mechanism is: After the inner block precision is ten from the outer local Context; leaving the outer block restores the earlier policy. For the library fines, add one near-miss that exposes assuming an inner block restores the application default rather than its immediate outer 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 assuming an inner block restores the application default rather than its immediate outer policy.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Trace precision before the outer block, inside both blocks, after the inner block and after the outer block.” 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 decimal.Context syntax. For this chapter, useful prompts are: “What did you expect from Nested local contexts restore in stack order?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing assuming an inner block restores the application default rather than its immediate outer policy 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 precision, exponent bounds, flags, traps, floats and nested local contexts. Include one ordinary case, one boundary and one deliberate failure caused by assuming an inner block restores the application default rather than its immediate outer 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: Each localcontext block copies the policy visible at entry, so nested temporary changes unwind last in, first out. It shows a trace, not only a final value. The ordinary case should demonstrate “After the inner block precision is ten from the outer local Context; leaving the outer block restores the earlier policy.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Trace precision before the outer block, inside both blocks, after the inner block and after the outer block. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Nested local contexts restore in stack order, separate the documented Python decimal.Context 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. Concurrency needs deliberate policy boundaries

Back to contents

The current Decimal context follows Python execution-context rules, so concurrent work should establish policy explicitly rather than rely on accidental inheritance. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.

The high-value mistake in this chapter is mutating a current context in one task and assuming every worker observes the same object. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Set policy at a task or worker boundary and pass explicit Context objects to shared helpers when reproducibility matters.

For the Concurrency needs deliberate policy boundaries chapter on Python decimal.Context, 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 mutating a current context in one task and assuming every worker observes the same object. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

def price_total(ctx,price,qty):
    return ctx.multiply(price,qty)

Explained result. The helper is deterministic with respect to the supplied policy instead of depending on whichever current Context happens to be active. 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: family planner. Explain the rule using temporary calculation policy that must not leak into later work. 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 current Decimal context follows Python execution-context rules, so concurrent work should establish policy explicitly rather than rely on accidental inheritance.” Apply this procedure: Set policy at a task or worker boundary and pass explicit Context objects to shared helpers when reproducibility matters. The expected mechanism is: The helper is deterministic with respect to the supplied policy instead of depending on whichever current Context happens to be active. For the family planner, add one near-miss that exposes mutating a current context in one task and assuming every worker observes the same object. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: library fines. Transfer the rule using daily charges, caps and a flag report for rounded results. 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 current Decimal context follows Python execution-context rules, so concurrent work should establish policy explicitly rather than rely on accidental inheritance.” Apply this procedure: Set policy at a task or worker boundary and pass explicit Context objects to shared helpers when reproducibility matters. The expected mechanism is: The helper is deterministic with respect to the supplied policy instead of depending on whichever current Context happens to be active. For the library fines, add one near-miss that exposes mutating a current context in one task and assuming every worker observes the same object. 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 precision, exponent bounds, flags, traps, floats and nested local contexts. 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 current Decimal context follows Python execution-context rules, so concurrent work should establish policy explicitly rather than rely on accidental inheritance.” Apply this procedure: Set policy at a task or worker boundary and pass explicit Context objects to shared helpers when reproducibility matters. The expected mechanism is: The helper is deterministic with respect to the supplied policy instead of depending on whichever current Context happens to be active. For the test laboratory, add one near-miss that exposes mutating a current context in one task and assuming every worker observes the same object. 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 decision. Contrast the rule using Decimal context compared with float, Fraction and explicit quantize calls. 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 current Decimal context follows Python execution-context rules, so concurrent work should establish policy explicitly rather than rely on accidental inheritance.” Apply this procedure: Set policy at a task or worker boundary and pass explicit Context objects to shared helpers when reproducibility matters. The expected mechanism is: The helper is deterministic with respect to the supplied policy instead of depending on whichever current Context happens to be active. For the design decision, add one near-miss that exposes mutating a current context in one task and assuming every worker observes the same object. 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 mutating a current context in one task and assuming every worker observes the same object.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Set policy at a task or worker boundary and pass explicit Context objects to shared helpers when reproducibility matters.” and record the first changed observation.
  • Transfer check: repeat the rule in a second context and identify what remains invariant.

A parent does not need to know the final Python decimal.Context syntax. For this chapter, useful prompts are: “What did you expect from Concurrency needs deliberate policy boundaries?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing mutating a current context in one task and assuming every worker observes the same object be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny design decision with Decimal context compared with float, Fraction and explicit quantize calls. Include one ordinary case, one boundary and one deliberate failure caused by mutating a current context in one task and assuming every worker observes the same object. 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 current Decimal context follows Python execution-context rules, so concurrent work should establish policy explicitly rather than rely on accidental inheritance. It shows a trace, not only a final value. The ordinary case should demonstrate “The helper is deterministic with respect to the supplied policy instead of depending on whichever current Context happens to be active.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Set policy at a task or worker boundary and pass explicit Context objects to shared helpers when reproducibility matters. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Concurrency needs deliberate policy boundaries, separate the documented Python decimal.Context 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 and audit a complete decimal policy

Back to contents

A defensible policy states input conversion, precision, rounding, exponent range, traps, flag monitoring and output quantization rather than changing one setting in isolation. 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 copying a money snippet without documenting ties, intermediate precision or exceptional conditions. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Write policy as executable setup plus tests for ties, extremes, inexact work, zero division and float contamination.

For the Choose and audit a complete decimal policy chapter on Python decimal.Context, 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 copying a money snippet without documenting ties, intermediate precision or exceptional conditions. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from decimal import Context, ROUND_HALF_EVEN, FloatOperation
policy=Context(prec=28,rounding=ROUND_HALF_EVEN)
policy.traps[FloatOperation]=True

Explained result. The Context expresses key arithmetic choices, while explicit quantize and flag checks complete the application-specific boundary. 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 precision, exponent bounds, flags, traps, floats and nested local contexts. 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 defensible policy states input conversion, precision, rounding, exponent range, traps, flag monitoring and output quantization rather than changing one setting in isolation.” Apply this procedure: Write policy as executable setup plus tests for ties, extremes, inexact work, zero division and float contamination. The expected mechanism is: The Context expresses key arithmetic choices, while explicit quantize and flag checks complete the application-specific boundary. For the test laboratory, add one near-miss that exposes copying a money snippet without documenting ties, intermediate precision or exceptional conditions. 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 decision. Predict the rule using Decimal context compared with float, Fraction and explicit quantize calls. 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 defensible policy states input conversion, precision, rounding, exponent range, traps, flag monitoring and output quantization rather than changing one setting in isolation.” Apply this procedure: Write policy as executable setup plus tests for ties, extremes, inexact work, zero division and float contamination. The expected mechanism is: The Context expresses key arithmetic choices, while explicit quantize and flag checks complete the application-specific boundary. For the design decision, add one near-miss that exposes copying a money snippet without documenting ties, intermediate precision or exceptional conditions. 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: canteen budget. Contrast the rule using prices, quantities, discounts and a two-place reporting rule. 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 defensible policy states input conversion, precision, rounding, exponent range, traps, flag monitoring and output quantization rather than changing one setting in isolation.” Apply this procedure: Write policy as executable setup plus tests for ties, extremes, inexact work, zero division and float contamination. The expected mechanism is: The Context expresses key arithmetic choices, while explicit quantize and flag checks complete the application-specific boundary. For the canteen budget, add one near-miss that exposes copying a money snippet without documenting ties, intermediate precision or exceptional conditions. 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: reading tracker. Stress-test the rule using percentage completion calculated under a stated precision. 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 defensible policy states input conversion, precision, rounding, exponent range, traps, flag monitoring and output quantization rather than changing one setting in isolation.” Apply this procedure: Write policy as executable setup plus tests for ties, extremes, inexact work, zero division and float contamination. The expected mechanism is: The Context expresses key arithmetic choices, while explicit quantize and flag checks complete the application-specific boundary. For the reading tracker, add one near-miss that exposes copying a money snippet without documenting ties, intermediate precision or exceptional conditions. 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 copying a money snippet without documenting ties, intermediate precision or exceptional conditions.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Write policy as executable setup plus tests for ties, extremes, inexact work, zero division and float contamination.” 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 decimal.Context syntax. For this chapter, useful prompts are: “What did you expect from Choose and audit a complete decimal policy?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing copying a money snippet without documenting ties, intermediate precision or exceptional conditions be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny canteen budget with prices, quantities, discounts and a two-place reporting rule. Include one ordinary case, one boundary and one deliberate failure caused by copying a money snippet without documenting ties, intermediate precision or exceptional conditions. 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 defensible policy states input conversion, precision, rounding, exponent range, traps, flag monitoring and output quantization rather than changing one setting in isolation. It shows a trace, not only a final value. The ordinary case should demonstrate “The Context expresses key arithmetic choices, while explicit quantize and flag checks complete the application-specific boundary.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Write policy as executable setup plus tests for ties, extremes, inexact work, zero division and float contamination. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Choose and audit a complete decimal policy, separate the documented Python decimal.Context 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. canteen budget: model, boundary and recovery

Create a small canteen budget using prices, quantities, discounts and a two-place reporting rule. Combine “Context is the arithmetic environment” 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 Context supplies precision, rounding, exponent limits, flags and traps for Decimal operations; it is not the Decimal value itself. Apply: Write the value and the active arithmetic policy in separate boxes, then run one operation that requires rounding. Verify: Division consults the current precision and produces Decimal(‘0.1429’); the input Decimals remain immutable values. 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. reading tracker: model, boundary and recovery

Create a small reading tracker using percentage completion calculated under a stated precision. Combine “setcontext installs a chosen policy” 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: setcontext() installs a copy of the supplied Context as current, useful when an application establishes one explicit arithmetic policy. Apply: Build a named Context, install it at a controlled boundary and verify settings before calculating. Verify: Subsequent context-sensitive arithmetic uses ten significant digits and half-up rounding in that execution context. 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. science practical: model, boundary and recovery

Create a small science practical using measured values with significant digits and an inexact-result audit. Combine “Rounding mode is a named policy” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.

Explained route. Start with: The rounding attribute selects one documented mode whenever an operation must discard digits. Apply: Use an exact tie and compare ROUND_HALF_EVEN with ROUND_HALF_UP at the same target exponent. Verify: The results are 2 and 3, proving that a tie policy is substantive input rather than decoration. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.

4. CCA fundraiser: model, boundary and recovery

Create a small CCA fundraiser using cash totals, percentage adjustments and explicit half-up rounding. Combine “Flags are sticky evidence” 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: When a signal occurs its flag becomes true and stays true until cleared, allowing a calculation block to be audited after it runs. Apply: Clear flags immediately before the monitored block and inspect them immediately after it. Verify: Rounded and Inexact are recorded for the repeating division, and remain recorded until explicitly cleared. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.

5. family planner: model, boundary and recovery

Create a small family planner using temporary calculation policy that must not leak into later work. Combine “DivisionByZero can be trapped or represented” 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: With its trap disabled, DivisionByZero can return an infinity and set a flag; with the trap enabled it raises an exception. Apply: Run the same operation under copied contexts with the trap disabled and enabled. Verify: The explicit Context returns Infinity and records the condition because its DivisionByZero trap is disabled. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.

6. library fines: model, boundary and recovery

Create a small library fines using daily charges, caps and a flag report for rounded results. Combine “copy separates later mutations” 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: Context.copy() creates a distinct Context with the same settings and current status at that moment, allowing a derived policy to change independently. Apply: Compare identity, change precision on the copy and inspect both objects. Verify: The copied policy can move to precision twelve without changing base precision. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.

7. test laboratory: model, boundary and recovery

Create a small test laboratory using precision, exponent bounds, flags, traps, floats and nested local contexts. Combine “Concurrency needs deliberate policy boundaries” with one later chapter. Include an ordinary case, a boundary, a deliberate failure and a recovery. Write the expected state before each operation.

Explained route. Start with: The current Decimal context follows Python execution-context rules, so concurrent work should establish policy explicitly rather than rely on accidental inheritance. Apply: Set policy at a task or worker boundary and pass explicit Context objects to shared helpers when reproducibility matters. Verify: The helper is deterministic with respect to the supplied policy instead of depending on whichever current Context happens to be active. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.

8. design decision: model, boundary and recovery

Create a small design decision using Decimal context compared with float, Fraction and explicit quantize calls. Combine “Construction and arithmetic are different stages” 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: Constructing a Decimal from a valid string preserves the digits supplied even when active precision is smaller; later arithmetic applies context rules. Apply: Construct a long string under low precision, inspect it, then add zero and compare the results. Verify: x retains 1.23456, while the arithmetic operation rounds its result to 1.23 under the three-digit context. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.

Frequently asked questions

How long should a practice session be?

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

Should every option or function be memorised?

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

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

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

Is the shortest solution the best?

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

When should official documentation be used?

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

How can a parent help without technical expertise?

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

How do we test transfer?

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

What should be saved after practice?

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

Can these exercises replace backups?

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

What counts as mastery?

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

Official and supporting references

Return to contents

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

eduKate Punggol

Contact

83 Punggol Central, Singapore 828761

edu|Kate Bukit Timah

8 Fourth Avenue, Singapore 268674

By Appointment +65 8823 1234
admin@edukatesg.com

Email Us

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

← 返回

感谢您的回复。 ✨

了解 eduKate Punggol 的更多信息

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

继续阅读