Small Group Tutorials

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

How to Master Python contextlib.chdir in Punggol Tuition

Entrance to Block E6 at Singapore Institute of Technology's Punggol Campus.

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 contextlib.chdir(path) temporarily changes the process current working directory when a with block begins and restores the earlier directory when the block ends. Mastery means treating that directory as global process state, reasoning about every relative path used while it is active, and refusing the helper in threaded, asynchronous or non-linear control flow where another task could observe the temporary state. This guide begins with that mechanism, then develops it through worked traces, deliberate mistakes, explained practice and transfer decisions.

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

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

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

Find your next learning step

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

Build the model

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

Use the core tools

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

Handle boundaries

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

Debug and verify

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

Transfer with judgment

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

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

CHAPTER 1 OF 20 . Build the model

1. The context manager changes one process-wide directory

Back to contents

Entering contextlib.chdir(path) calls the operating-system directory change and leaving restores the directory that was current before entry. 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 the block as though it changes only one function or Path object. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Print Path.cwd() before, inside and after a block in a disposable directory.

For the The context manager changes one process-wide directory chapter on Python contextlib.chdir, 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 the block as though it changes only one function or Path object. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from contextlib import chdir
from pathlib import Path
old=Path.cwd()
with chdir('/tmp'):
    print(Path.cwd())
print(Path.cwd()==old)

Explained result. Inside the block the process directory is /tmp; after normal exit the original directory is restored. 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: homework file sorter. Predict the rule using a disposable folder of draft answers and reviewed answers. 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 “Entering contextlib.chdir(path) calls the operating-system directory change and leaving restores the directory that was current before entry.” Apply this procedure: Print Path.cwd() before, inside and after a block in a disposable directory. The expected mechanism is: Inside the block the process directory is /tmp; after normal exit the original directory is restored. For the homework file sorter, add one near-miss that exposes describing the block as though it changes only one function or Path 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 export. Contrast the rule using relative CSV inputs and an absolute archive destination. 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 “Entering contextlib.chdir(path) calls the operating-system directory change and leaving restores the directory that was current before entry.” Apply this procedure: Print Path.cwd() before, inside and after a block in a disposable directory. The expected mechanism is: Inside the block the process directory is /tmp; after normal exit the original directory is restored. For the library export, add one near-miss that exposes describing the block as though it changes only one function or Path 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: CCA registration tool. Stress-test the rule using configuration files and generated attendance sheets. 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 “Entering contextlib.chdir(path) calls the operating-system directory change and leaving restores the directory that was current before entry.” Apply this procedure: Print Path.cwd() before, inside and after a block in a disposable directory. The expected mechanism is: Inside the block the process directory is /tmp; after normal exit the original directory is restored. For the CCA registration tool, add one near-miss that exposes describing the block as though it changes only one function or Path 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: science-data script. Explain the rule using a temporary run directory with readings and charts. 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 “Entering contextlib.chdir(path) calls the operating-system directory change and leaving restores the directory that was current before entry.” Apply this procedure: Print Path.cwd() before, inside and after a block in a disposable directory. The expected mechanism is: Inside the block the process directory is /tmp; after normal exit the original directory is restored. For the science-data script, add one near-miss that exposes describing the block as though it changes only one function or Path 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 describing the block as though it changes only one function or Path object.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Print Path.cwd() before, inside and after a block in a disposable directory.” 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 contextlib.chdir syntax. For this chapter, useful prompts are: “What did you expect from The context manager changes one process-wide directory?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing describing the block as though it changes only one function or Path object be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny photo-index exercise with sample image names and a generated catalogue. Include one ordinary case, one boundary and one deliberate failure caused by describing the block as though it changes only one function or Path 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: Entering contextlib.chdir(path) calls the operating-system directory change and leaving restores the directory that was current before entry. It shows a trace, not only a final value. The ordinary case should demonstrate “Inside the block the process directory is /tmp; after normal exit the original directory is restored.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Print Path.cwd() before, inside and after a block in a disposable directory. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For The context manager changes one process-wide directory, separate the documented Python contextlib.chdir 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. The as-target is None

Back to contents

contextlib.chdir manages state but its __enter__ result is None, so with chdir(path) as value does not bind the destination Path. 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 the as-target as though it were an opened directory handle. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Keep the destination in an explicit Path variable and inspect cwd separately.

For the The as-target is None chapter on Python contextlib.chdir, 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 the as-target as though it were an opened directory handle. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from contextlib import chdir
from pathlib import Path
dest=Path('/tmp')
with chdir(dest) as entered:
    print(entered, Path.cwd())

Explained result. entered is None while Path.cwd() reports the temporary directory. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: CCA registration tool. Contrast the rule using configuration files and generated attendance sheets. 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 “contextlib.chdir manages state but its __enter__ result is None, so with chdir(path) as value does not bind the destination Path.” Apply this procedure: Keep the destination in an explicit Path variable and inspect cwd separately. The expected mechanism is: entered is None while Path.cwd() reports the temporary directory. For the CCA registration tool, add one near-miss that exposes using the as-target as though it were an opened directory 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: science-data script. Stress-test the rule using a temporary run directory with readings and charts. 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 “contextlib.chdir manages state but its __enter__ result is None, so with chdir(path) as value does not bind the destination Path.” Apply this procedure: Keep the destination in an explicit Path variable and inspect cwd separately. The expected mechanism is: entered is None while Path.cwd() reports the temporary directory. For the science-data script, add one near-miss that exposes using the as-target as though it were an opened directory 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: revision-note builder. Explain the rule using Markdown sources and an output folder. 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 “contextlib.chdir manages state but its __enter__ result is None, so with chdir(path) as value does not bind the destination Path.” Apply this procedure: Keep the destination in an explicit Path variable and inspect cwd separately. The expected mechanism is: entered is None while Path.cwd() reports the temporary directory. For the revision-note builder, add one near-miss that exposes using the as-target as though it were an opened directory 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: photo-index exercise. Transfer the rule using sample image names and a generated catalogue. 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 “contextlib.chdir manages state but its __enter__ result is None, so with chdir(path) as value does not bind the destination Path.” Apply this procedure: Keep the destination in an explicit Path variable and inspect cwd separately. The expected mechanism is: entered is None while Path.cwd() reports the temporary directory. For the photo-index exercise, add one near-miss that exposes using the as-target as though it were an opened directory 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 using the as-target as though it were an opened directory handle.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Keep the destination in an explicit Path variable and inspect cwd separately.” and record the first changed observation.
  • Transfer check: repeat the rule in a second context and identify what remains invariant.

A parent does not need to know the final Python contextlib.chdir syntax. For this chapter, useful prompts are: “What did you expect from The as-target is None?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing using the as-target as though it were an opened directory handle be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny budget practice app with relative data files and an exported summary. Include one ordinary case, one boundary and one deliberate failure caused by using the as-target as though it were an opened directory 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: contextlib.chdir manages state but its __enter__ result is None, so with chdir(path) as value does not bind the destination Path. It shows a trace, not only a final value. The ordinary case should demonstrate “entered is None while Path.cwd() reports the temporary directory.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Keep the destination in an explicit Path variable and inspect cwd separately. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For The as-target is None, separate the documented Python contextlib.chdir 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. Path-like inputs follow os.chdir rules

Back to contents

The path argument is passed to os.chdir, so strings, bytes where supported and objects implementing the path protocol follow platform path 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 assuming the helper normalises, creates or validates a project directory in advance. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Resolve and validate the intended directory before entering when the boundary matters.

For the Path-like inputs follow os.chdir rules chapter on Python contextlib.chdir, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on assuming the helper normalises, creates or validates a project directory in advance. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from contextlib import chdir
from pathlib import Path
p=Path('/tmp')
with chdir(p):
    print(Path.cwd().name)

Explained result. A pathlib.Path is accepted through the path protocol; the helper does not create missing directories. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: revision-note builder. Stress-test the rule using Markdown sources and an output folder. 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 path argument is passed to os.chdir, so strings, bytes where supported and objects implementing the path protocol follow platform path rules.” Apply this procedure: Resolve and validate the intended directory before entering when the boundary matters. The expected mechanism is: A pathlib.Path is accepted through the path protocol; the helper does not create missing directories. For the revision-note builder, add one near-miss that exposes assuming the helper normalises, creates or validates a project directory in advance. 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: photo-index exercise. Explain the rule using sample image names and a generated catalogue. 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 path argument is passed to os.chdir, so strings, bytes where supported and objects implementing the path protocol follow platform path rules.” Apply this procedure: Resolve and validate the intended directory before entering when the boundary matters. The expected mechanism is: A pathlib.Path is accepted through the path protocol; the helper does not create missing directories. For the photo-index exercise, add one near-miss that exposes assuming the helper normalises, creates or validates a project directory in advance. 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: budget practice app. Transfer the rule using relative data files and an exported summary. 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 path argument is passed to os.chdir, so strings, bytes where supported and objects implementing the path protocol follow platform path rules.” Apply this procedure: Resolve and validate the intended directory before entering when the boundary matters. The expected mechanism is: A pathlib.Path is accepted through the path protocol; the helper does not create missing directories. For the budget practice app, add one near-miss that exposes assuming the helper normalises, creates or validates a project directory in advance. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: project build rehearsal. Predict the rule using source folders, subprocesses and test artefacts. 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 path argument is passed to os.chdir, so strings, bytes where supported and objects implementing the path protocol follow platform path rules.” Apply this procedure: Resolve and validate the intended directory before entering when the boundary matters. The expected mechanism is: A pathlib.Path is accepted through the path protocol; the helper does not create missing directories. For the project build rehearsal, add one near-miss that exposes assuming the helper normalises, creates or validates a project directory in advance. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Diagnostic route

  • Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
  • Boundary check: create the smallest input that triggers assuming the helper normalises, creates or validates a project directory in advance.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Resolve and validate the intended directory before entering when the boundary 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 contextlib.chdir syntax. For this chapter, useful prompts are: “What did you expect from Path-like inputs follow os.chdir rules?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing assuming the helper normalises, creates or validates a project directory in advance be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny project build rehearsal with source folders, subprocesses and test artefacts. Include one ordinary case, one boundary and one deliberate failure caused by assuming the helper normalises, creates or validates a project directory in advance. 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 path argument is passed to os.chdir, so strings, bytes where supported and objects implementing the path protocol follow platform path rules. It shows a trace, not only a final value. The ordinary case should demonstrate “A pathlib.Path is accepted through the path protocol; the helper does not create missing directories.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Resolve and validate the intended directory before entering when the boundary matters. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Path-like inputs follow os.chdir rules, separate the documented Python contextlib.chdir 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. A relative destination is resolved at entry

Back to contents

A relative path is interpreted from the current working directory at the moment the context is entered. 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 a relative destination as though it were anchored to the Python file. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Capture an absolute base Path before entry and construct destinations from that base.

For the A relative destination is resolved at entry chapter on Python contextlib.chdir, 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 a relative destination as though it were anchored to the Python file. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from pathlib import Path
base=Path.cwd()
dest=(base/'sandbox').resolve()
# with chdir(dest): ...

Explained result. The explicit absolute destination remains anchored to the intended base even if surrounding code later changes directory. 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: budget practice app. Explain the rule using relative data files and an exported summary. 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 relative path is interpreted from the current working directory at the moment the context is entered.” Apply this procedure: Capture an absolute base Path before entry and construct destinations from that base. The expected mechanism is: The explicit absolute destination remains anchored to the intended base even if surrounding code later changes directory. For the budget practice app, add one near-miss that exposes reading a relative destination as though it were anchored to the Python file. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: project build rehearsal. Transfer the rule using source folders, subprocesses and test artefacts. 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 relative path is interpreted from the current working directory at the moment the context is entered.” Apply this procedure: Capture an absolute base Path before entry and construct destinations from that base. The expected mechanism is: The explicit absolute destination remains anchored to the intended base even if surrounding code later changes directory. For the project build rehearsal, add one near-miss that exposes reading a relative destination as though it were anchored to the Python file. 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: homework file sorter. Predict the rule using a disposable folder of draft answers and reviewed answers. 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 relative path is interpreted from the current working directory at the moment the context is entered.” Apply this procedure: Capture an absolute base Path before entry and construct destinations from that base. The expected mechanism is: The explicit absolute destination remains anchored to the intended base even if surrounding code later changes directory. For the homework file sorter, add one near-miss that exposes reading a relative destination as though it were anchored to the Python file. 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 export. Contrast the rule using relative CSV inputs and an absolute archive destination. 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 relative path is interpreted from the current working directory at the moment the context is entered.” Apply this procedure: Capture an absolute base Path before entry and construct destinations from that base. The expected mechanism is: The explicit absolute destination remains anchored to the intended base even if surrounding code later changes directory. For the library export, add one near-miss that exposes reading a relative destination as though it were anchored to the Python file. 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 a relative destination as though it were anchored to the Python file.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Capture an absolute base Path before entry and construct destinations from that base.” 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 contextlib.chdir syntax. For this chapter, useful prompts are: “What did you expect from A relative destination is resolved at entry?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing reading a relative destination as though it were anchored to the Python file be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny homework file sorter with a disposable folder of draft answers and reviewed answers. Include one ordinary case, one boundary and one deliberate failure caused by reading a relative destination as though it were anchored to the Python file. 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 relative path is interpreted from the current working directory at the moment the context is entered. It shows a trace, not only a final value. The ordinary case should demonstrate “The explicit absolute destination remains anchored to the intended base even if surrounding code later changes directory.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Capture an absolute base Path before entry and construct destinations from that base. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For A relative destination is resolved at entry, separate the documented Python contextlib.chdir 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. Normal exit restores the earlier directory

Back to contents

The finally logic runs when the with body completes, returning the process to the saved directory. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.

The high-value mistake in this chapter is adding a second manual chdir after the block and accidentally restoring to the wrong place. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Assert the before and after paths in a small test instead of duplicating cleanup.

For the Normal exit restores the earlier directory chapter on Python contextlib.chdir, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on adding a second manual chdir after the block and accidentally restoring to the wrong place. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from contextlib import chdir
from pathlib import Path
before=Path.cwd()
with chdir('/tmp'):
    pass
assert Path.cwd()==before

Explained result. The assertion passes when the original directory remains available. 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: homework file sorter. Transfer the rule using a disposable folder of draft answers and reviewed answers. 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 finally logic runs when the with body completes, returning the process to the saved directory.” Apply this procedure: Assert the before and after paths in a small test instead of duplicating cleanup. The expected mechanism is: The assertion passes when the original directory remains available. For the homework file sorter, add one near-miss that exposes adding a second manual chdir after the block and accidentally restoring to the wrong place. 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 export. Predict the rule using relative CSV inputs and an absolute archive destination. 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 finally logic runs when the with body completes, returning the process to the saved directory.” Apply this procedure: Assert the before and after paths in a small test instead of duplicating cleanup. The expected mechanism is: The assertion passes when the original directory remains available. For the library export, add one near-miss that exposes adding a second manual chdir after the block and accidentally restoring to the wrong place. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: CCA registration tool. Contrast the rule using configuration files and generated attendance sheets. 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 finally logic runs when the with body completes, returning the process to the saved directory.” Apply this procedure: Assert the before and after paths in a small test instead of duplicating cleanup. The expected mechanism is: The assertion passes when the original directory remains available. For the CCA registration tool, add one near-miss that exposes adding a second manual chdir after the block and accidentally restoring to the wrong place. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: science-data script. Stress-test the rule using a temporary run directory with readings and charts. 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 finally logic runs when the with body completes, returning the process to the saved directory.” Apply this procedure: Assert the before and after paths in a small test instead of duplicating cleanup. The expected mechanism is: The assertion passes when the original directory remains available. For the science-data script, add one near-miss that exposes adding a second manual chdir after the block and accidentally restoring to the wrong place. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Diagnostic route

  • Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
  • Boundary check: create the smallest input that triggers adding a second manual chdir after the block and accidentally restoring to the wrong place.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Assert the before and after paths in a small test instead of duplicating cleanup.” 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 contextlib.chdir syntax. For this chapter, useful prompts are: “What did you expect from Normal exit restores the earlier directory?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing adding a second manual chdir after the block and accidentally restoring to the wrong place be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny library export with relative CSV inputs and an absolute archive destination. Include one ordinary case, one boundary and one deliberate failure caused by adding a second manual chdir after the block and accidentally restoring to the wrong place. 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 finally logic runs when the with body completes, returning the process to the saved directory. It shows a trace, not only a final value. The ordinary case should demonstrate “The assertion passes when the original directory remains available.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Assert the before and after paths in a small test instead of duplicating cleanup. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Normal exit restores the earlier directory, separate the documented Python contextlib.chdir 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. Exceptional exit also attempts restoration

Back to contents

The context manager restores the saved directory in a finally path even when the body raises. 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 catching the exception inside the block and concluding restoration caused the error. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Catch outside the with statement and record both exception type and final cwd.

For the Exceptional exit also attempts restoration chapter on Python contextlib.chdir, 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 catching the exception inside the block and concluding restoration caused the error. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from contextlib import chdir
from pathlib import Path
before=Path.cwd()
try:
    with chdir('/tmp'):
        raise RuntimeError('stop')
except RuntimeError:
    pass
print(Path.cwd()==before)

Explained result. The final comparison prints True, so restoration is observable even though the body raises. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: CCA registration tool. Predict the rule using configuration files and generated attendance sheets. 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 context manager restores the saved directory in a finally path even when the body raises.” Apply this procedure: Catch outside the with statement and record both exception type and final cwd. The expected mechanism is: The final comparison prints True, so restoration is observable even though the body raises. For the CCA registration tool, add one near-miss that exposes catching the exception inside the block and concluding restoration caused the error. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: science-data script. Contrast the rule using a temporary run directory with readings and charts. 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 context manager restores the saved directory in a finally path even when the body raises.” Apply this procedure: Catch outside the with statement and record both exception type and final cwd. The expected mechanism is: The final comparison prints True, so restoration is observable even though the body raises. For the science-data script, add one near-miss that exposes catching the exception inside the block and concluding restoration caused the error. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: revision-note builder. Stress-test the rule using Markdown sources and an output folder. 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 context manager restores the saved directory in a finally path even when the body raises.” Apply this procedure: Catch outside the with statement and record both exception type and final cwd. The expected mechanism is: The final comparison prints True, so restoration is observable even though the body raises. For the revision-note builder, add one near-miss that exposes catching the exception inside the block and concluding restoration caused the error. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: photo-index exercise. Explain the rule using sample image names and a generated catalogue. 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 context manager restores the saved directory in a finally path even when the body raises.” Apply this procedure: Catch outside the with statement and record both exception type and final cwd. The expected mechanism is: The final comparison prints True, so restoration is observable even though the body raises. For the photo-index exercise, add one near-miss that exposes catching the exception inside the block and concluding restoration caused the error. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Diagnostic route

  • Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
  • Boundary check: create the smallest input that triggers catching the exception inside the block and concluding restoration caused the error.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Catch outside the with statement and record both exception type and final cwd.” 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 contextlib.chdir syntax. For this chapter, useful prompts are: “What did you expect from Exceptional exit also attempts restoration?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing catching the exception inside the block and concluding restoration caused the error be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny CCA registration tool with configuration files and generated attendance sheets. Include one ordinary case, one boundary and one deliberate failure caused by catching the exception inside the block and concluding restoration caused the error. Predict each result before using a tool, then report the first point where observation differs from prediction.

Answer guide. A strong response starts with the rule: The context manager restores the saved directory in a finally path even when the body raises. It shows a trace, not only a final value. The ordinary case should demonstrate “The final comparison prints True, so restoration is observable even though the body raises.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Catch outside the with statement and record both exception type and final cwd. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Exceptional exit also attempts restoration, separate the documented Python contextlib.chdir 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. Nested use is reentrant

Back to contents

Each entry saves the directory current at that level, so an inner block restores to the outer temporary directory before the outer block restores to the start. 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 every nested exit jumps directly to the program startup directory. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Print a three-row trace for start, outer, inner, outer-restored and final-restored states.

For the Nested use is reentrant chapter on Python contextlib.chdir, 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 every nested exit jumps directly to the program startup directory. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from contextlib import chdir
from pathlib import Path
with chdir('/tmp'):
    outer=Path.cwd()
    with chdir('/'):
        print(Path.cwd())
    print(Path.cwd()==outer)

Explained result. The inner exit returns to /tmp, and the outer exit later returns to the directory that preceded the outer block. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: revision-note builder. Contrast the rule using Markdown sources and an output folder. 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 entry saves the directory current at that level, so an inner block restores to the outer temporary directory before the outer block restores to the start.” Apply this procedure: Print a three-row trace for start, outer, inner, outer-restored and final-restored states. The expected mechanism is: The inner exit returns to /tmp, and the outer exit later returns to the directory that preceded the outer block. For the revision-note builder, add one near-miss that exposes assuming every nested exit jumps directly to the program startup directory. 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: photo-index exercise. Stress-test the rule using sample image names and a generated catalogue. 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 entry saves the directory current at that level, so an inner block restores to the outer temporary directory before the outer block restores to the start.” Apply this procedure: Print a three-row trace for start, outer, inner, outer-restored and final-restored states. The expected mechanism is: The inner exit returns to /tmp, and the outer exit later returns to the directory that preceded the outer block. For the photo-index exercise, add one near-miss that exposes assuming every nested exit jumps directly to the program startup directory. 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: budget practice app. Explain the rule using relative data files and an exported summary. 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 entry saves the directory current at that level, so an inner block restores to the outer temporary directory before the outer block restores to the start.” Apply this procedure: Print a three-row trace for start, outer, inner, outer-restored and final-restored states. The expected mechanism is: The inner exit returns to /tmp, and the outer exit later returns to the directory that preceded the outer block. For the budget practice app, add one near-miss that exposes assuming every nested exit jumps directly to the program startup directory. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: project build rehearsal. Transfer the rule using source folders, subprocesses and test artefacts. 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 entry saves the directory current at that level, so an inner block restores to the outer temporary directory before the outer block restores to the start.” Apply this procedure: Print a three-row trace for start, outer, inner, outer-restored and final-restored states. The expected mechanism is: The inner exit returns to /tmp, and the outer exit later returns to the directory that preceded the outer block. For the project build rehearsal, add one near-miss that exposes assuming every nested exit jumps directly to the program startup directory. 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 every nested exit jumps directly to the program startup directory.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Print a three-row trace for start, outer, inner, outer-restored and final-restored states.” 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 contextlib.chdir syntax. For this chapter, useful prompts are: “What did you expect from Nested use is reentrant?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing assuming every nested exit jumps directly to the program startup directory be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny science-data script with a temporary run directory with readings and charts. Include one ordinary case, one boundary and one deliberate failure caused by assuming every nested exit jumps directly to the program startup directory. 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 entry saves the directory current at that level, so an inner block restores to the outer temporary directory before the outer block restores to the start. It shows a trace, not only a final value. The ordinary case should demonstrate “The inner exit returns to /tmp, and the outer exit later returns to the directory that preceded the outer block.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Print a three-row trace for start, outer, inner, outer-restored and final-restored states. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Nested use is reentrant, separate the documented Python contextlib.chdir 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. The state is global, not thread-local

Back to contents

The process current directory is shared by threads, so another thread can resolve relative paths against the temporary directory. 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 a short with block thread-safe merely because it ends quickly. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Use absolute paths in concurrent programs and keep chdir out of threaded library code.

For the The state is global, not thread-local chapter on Python contextlib.chdir, 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 a short with block thread-safe merely because it ends quickly. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

# Unsafe design idea:
# thread A: with chdir(run_dir): read('input.txt')
# thread B: open('settings.json')

Explained result. Thread B can observe thread A’s temporary directory because cwd belongs to the process rather than to one thread. 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: budget practice app. Stress-test the rule using relative data files and an exported summary. 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 process current directory is shared by threads, so another thread can resolve relative paths against the temporary directory.” Apply this procedure: Use absolute paths in concurrent programs and keep chdir out of threaded library code. The expected mechanism is: Thread B can observe thread A’s temporary directory because cwd belongs to the process rather than to one thread. For the budget practice app, add one near-miss that exposes calling a short with block thread-safe merely because it ends quickly. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: project build rehearsal. Explain the rule using source folders, subprocesses and test artefacts. 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 process current directory is shared by threads, so another thread can resolve relative paths against the temporary directory.” Apply this procedure: Use absolute paths in concurrent programs and keep chdir out of threaded library code. The expected mechanism is: Thread B can observe thread A’s temporary directory because cwd belongs to the process rather than to one thread. For the project build rehearsal, add one near-miss that exposes calling a short with block thread-safe merely because it ends quickly. 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: homework file sorter. Transfer the rule using a disposable folder of draft answers and reviewed answers. 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 process current directory is shared by threads, so another thread can resolve relative paths against the temporary directory.” Apply this procedure: Use absolute paths in concurrent programs and keep chdir out of threaded library code. The expected mechanism is: Thread B can observe thread A’s temporary directory because cwd belongs to the process rather than to one thread. For the homework file sorter, add one near-miss that exposes calling a short with block thread-safe merely because it ends quickly. 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 export. Predict the rule using relative CSV inputs and an absolute archive destination. 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 process current directory is shared by threads, so another thread can resolve relative paths against the temporary directory.” Apply this procedure: Use absolute paths in concurrent programs and keep chdir out of threaded library code. The expected mechanism is: Thread B can observe thread A’s temporary directory because cwd belongs to the process rather than to one thread. For the library export, add one near-miss that exposes calling a short with block thread-safe merely because it ends quickly. 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 a short with block thread-safe merely because it ends quickly.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Use absolute paths in concurrent programs and keep chdir out of threaded library code.” and record the first changed observation.
  • Transfer check: repeat the rule in a second context and identify what remains invariant.

A parent does not need to know the final Python contextlib.chdir syntax. For this chapter, useful prompts are: “What did you expect from The state is global, not thread-local?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing calling a short with block thread-safe merely because it ends quickly be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny revision-note builder with Markdown sources and an output folder. Include one ordinary case, one boundary and one deliberate failure caused by calling a short with block thread-safe merely because it ends quickly. 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 process current directory is shared by threads, so another thread can resolve relative paths against the temporary directory. It shows a trace, not only a final value. The ordinary case should demonstrate “Thread B can observe thread A’s temporary directory because cwd belongs to the process rather than to one thread.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Use absolute paths in concurrent programs and keep chdir out of threaded library code. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For The state is global, not thread-local, separate the documented Python contextlib.chdir 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. Async tasks can interleave while cwd is changed

Back to contents

An await can hand control to another task while the global directory still points at the temporary destination. 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 async with-style reasoning for a synchronous global state change. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Do not await inside the block; prefer absolute paths passed to each operation.

For the Async tasks can interleave while cwd is changed chapter on Python contextlib.chdir, 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 async with-style reasoning for a synchronous global state change. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

# Avoid:
# with chdir(run_dir):
#     await do_other_work()

Explained result. The await creates an interval in which unrelated tasks may perform relative I/O against run_dir. 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: homework file sorter. Explain the rule using a disposable folder of draft answers and reviewed answers. 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 “An await can hand control to another task while the global directory still points at the temporary destination.” Apply this procedure: Do not await inside the block; prefer absolute paths passed to each operation. The expected mechanism is: The await creates an interval in which unrelated tasks may perform relative I/O against run_dir. For the homework file sorter, add one near-miss that exposes using async with-style reasoning for a synchronous global state change. 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 export. Transfer the rule using relative CSV inputs and an absolute archive destination. 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 “An await can hand control to another task while the global directory still points at the temporary destination.” Apply this procedure: Do not await inside the block; prefer absolute paths passed to each operation. The expected mechanism is: The await creates an interval in which unrelated tasks may perform relative I/O against run_dir. For the library export, add one near-miss that exposes using async with-style reasoning for a synchronous global state change. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: CCA registration tool. Predict the rule using configuration files and generated attendance sheets. 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 “An await can hand control to another task while the global directory still points at the temporary destination.” Apply this procedure: Do not await inside the block; prefer absolute paths passed to each operation. The expected mechanism is: The await creates an interval in which unrelated tasks may perform relative I/O against run_dir. For the CCA registration tool, add one near-miss that exposes using async with-style reasoning for a synchronous global state change. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: science-data script. Contrast the rule using a temporary run directory with readings and charts. 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 “An await can hand control to another task while the global directory still points at the temporary destination.” Apply this procedure: Do not await inside the block; prefer absolute paths passed to each operation. The expected mechanism is: The await creates an interval in which unrelated tasks may perform relative I/O against run_dir. For the science-data script, add one near-miss that exposes using async with-style reasoning for a synchronous global state change. 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 async with-style reasoning for a synchronous global state change.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Do not await inside the block; prefer absolute paths passed to each 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 contextlib.chdir syntax. For this chapter, useful prompts are: “What did you expect from Async tasks can interleave while cwd is changed?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing using async with-style reasoning for a synchronous global state change be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny photo-index exercise with sample image names and a generated catalogue. Include one ordinary case, one boundary and one deliberate failure caused by using async with-style reasoning for a synchronous global state change. 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: An await can hand control to another task while the global directory still points at the temporary destination. It shows a trace, not only a final value. The ordinary case should demonstrate “The await creates an interval in which unrelated tasks may perform relative I/O against run_dir.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Do not await inside the block; prefer absolute paths passed to each operation. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Async tasks can interleave while cwd is changed, separate the documented Python contextlib.chdir 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. Generators make the lifetime non-linear

Back to contents

Yielding from inside the block suspends execution while leaving the process directory changed until iteration resumes or closes. 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 a generator restores state immediately after producing one value. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Materialise required values before yielding, or remove the directory change by using absolute paths.

For the Generators make the lifetime non-linear chapter on Python contextlib.chdir, 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 a generator restores state immediately after producing one value. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

def unsafe():
    from contextlib import chdir
    with chdir('/tmp'):
        yield 'paused while cwd is /tmp'

Explained result. After the first next call, the generator is suspended and the temporary cwd remains 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: CCA registration tool. Transfer the rule using configuration files and generated attendance sheets. 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 “Yielding from inside the block suspends execution while leaving the process directory changed until iteration resumes or closes.” Apply this procedure: Materialise required values before yielding, or remove the directory change by using absolute paths. The expected mechanism is: After the first next call, the generator is suspended and the temporary cwd remains active. For the CCA registration tool, add one near-miss that exposes assuming a generator restores state immediately after producing one value. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: science-data script. Predict the rule using a temporary run directory with readings and charts. 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 “Yielding from inside the block suspends execution while leaving the process directory changed until iteration resumes or closes.” Apply this procedure: Materialise required values before yielding, or remove the directory change by using absolute paths. The expected mechanism is: After the first next call, the generator is suspended and the temporary cwd remains active. For the science-data script, add one near-miss that exposes assuming a generator restores state immediately after producing one value. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: revision-note builder. Contrast the rule using Markdown sources and an output folder. 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 “Yielding from inside the block suspends execution while leaving the process directory changed until iteration resumes or closes.” Apply this procedure: Materialise required values before yielding, or remove the directory change by using absolute paths. The expected mechanism is: After the first next call, the generator is suspended and the temporary cwd remains active. For the revision-note builder, add one near-miss that exposes assuming a generator restores state immediately after producing one value. 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: photo-index exercise. Stress-test the rule using sample image names and a generated catalogue. 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 “Yielding from inside the block suspends execution while leaving the process directory changed until iteration resumes or closes.” Apply this procedure: Materialise required values before yielding, or remove the directory change by using absolute paths. The expected mechanism is: After the first next call, the generator is suspended and the temporary cwd remains active. For the photo-index exercise, add one near-miss that exposes assuming a generator restores state immediately after producing one value. 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 a generator restores state immediately after producing one value.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Materialise required values before yielding, or remove the directory change by using absolute paths.” 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 contextlib.chdir syntax. For this chapter, useful prompts are: “What did you expect from Generators make the lifetime non-linear?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing assuming a generator restores state immediately after producing one value be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny budget practice app with relative data files and an exported summary. Include one ordinary case, one boundary and one deliberate failure caused by assuming a generator restores state immediately after producing one value. 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: Yielding from inside the block suspends execution while leaving the process directory changed until iteration resumes or closes. It shows a trace, not only a final value. The ordinary case should demonstrate “After the first next call, the generator is suspended and the temporary cwd remains active.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Materialise required values before yielding, or remove the directory change by using absolute paths. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Generators make the lifetime non-linear, separate the documented Python contextlib.chdir 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. Relative file opens follow the temporary cwd

Back to contents

A new open call with a relative name resolves inside the active directory. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.

The high-value mistake in this chapter is believing only pathlib calls notice the changed directory. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. List the expected absolute target before opening and test with a temporary directory.

For the Relative file opens follow the temporary cwd chapter on Python contextlib.chdir, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on believing only pathlib calls notice the changed directory. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from contextlib import chdir
from pathlib import Path
with chdir('/tmp'):
    target=Path('notes.txt').resolve()
    print(target)

Explained result. The resolved target is /tmp/notes.txt on a POSIX system; no file is created merely by resolving it. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: revision-note builder. Predict the rule using Markdown sources and an output folder. 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 new open call with a relative name resolves inside the active directory.” Apply this procedure: List the expected absolute target before opening and test with a temporary directory. The expected mechanism is: The resolved target is /tmp/notes.txt on a POSIX system; no file is created merely by resolving it. For the revision-note builder, add one near-miss that exposes believing only pathlib calls notice the changed directory. 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: photo-index exercise. Contrast the rule using sample image names and a generated catalogue. 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 new open call with a relative name resolves inside the active directory.” Apply this procedure: List the expected absolute target before opening and test with a temporary directory. The expected mechanism is: The resolved target is /tmp/notes.txt on a POSIX system; no file is created merely by resolving it. For the photo-index exercise, add one near-miss that exposes believing only pathlib calls notice the changed directory. 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: budget practice app. Stress-test the rule using relative data files and an exported summary. 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 new open call with a relative name resolves inside the active directory.” Apply this procedure: List the expected absolute target before opening and test with a temporary directory. The expected mechanism is: The resolved target is /tmp/notes.txt on a POSIX system; no file is created merely by resolving it. For the budget practice app, add one near-miss that exposes believing only pathlib calls notice the changed directory. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: project build rehearsal. Explain the rule using source folders, subprocesses and test artefacts. 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 new open call with a relative name resolves inside the active directory.” Apply this procedure: List the expected absolute target before opening and test with a temporary directory. The expected mechanism is: The resolved target is /tmp/notes.txt on a POSIX system; no file is created merely by resolving it. For the project build rehearsal, add one near-miss that exposes believing only pathlib calls notice the changed directory. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Diagnostic route

  • Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
  • Boundary check: create the smallest input that triggers believing only pathlib calls notice the changed directory.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “List the expected absolute target before opening and test with a temporary directory.” 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 contextlib.chdir syntax. For this chapter, useful prompts are: “What did you expect from Relative file opens follow the temporary cwd?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing believing only pathlib calls notice the changed directory be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny project build rehearsal with source folders, subprocesses and test artefacts. Include one ordinary case, one boundary and one deliberate failure caused by believing only pathlib calls notice the changed directory. 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 new open call with a relative name resolves inside the active directory. It shows a trace, not only a final value. The ordinary case should demonstrate “The resolved target is /tmp/notes.txt on a POSIX system; no file is created merely by resolving it.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: List the expected absolute target before opening and test with a temporary directory. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Relative file opens follow the temporary cwd, separate the documented Python contextlib.chdir 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. Existing file handles do not retarget

Back to contents

An already-open file descriptor continues to refer to the same file when cwd changes; only later relative path resolution is affected. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.

The high-value mistake in this chapter is expecting an open handle to start reading a same-named file in the new directory. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Open before entry, compare its identity information and avoid reopening by relative name accidentally.

For the Existing file handles do not retarget chapter on Python contextlib.chdir, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on expecting an open handle to start reading a same-named file in the new directory. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

# handle=open(absolute_file)
# with chdir(other_dir): handle.read()

Explained result. The handle remains attached to the file opened earlier because changing cwd does not rewrite an existing descriptor. 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: budget practice app. Contrast the rule using relative data files and an exported summary. 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 “An already-open file descriptor continues to refer to the same file when cwd changes; only later relative path resolution is affected.” Apply this procedure: Open before entry, compare its identity information and avoid reopening by relative name accidentally. The expected mechanism is: The handle remains attached to the file opened earlier because changing cwd does not rewrite an existing descriptor. For the budget practice app, add one near-miss that exposes expecting an open handle to start reading a same-named file in the new directory. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: project build rehearsal. Stress-test the rule using source folders, subprocesses and test artefacts. 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 “An already-open file descriptor continues to refer to the same file when cwd changes; only later relative path resolution is affected.” Apply this procedure: Open before entry, compare its identity information and avoid reopening by relative name accidentally. The expected mechanism is: The handle remains attached to the file opened earlier because changing cwd does not rewrite an existing descriptor. For the project build rehearsal, add one near-miss that exposes expecting an open handle to start reading a same-named file in the new directory. 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: homework file sorter. Explain the rule using a disposable folder of draft answers and reviewed answers. 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 “An already-open file descriptor continues to refer to the same file when cwd changes; only later relative path resolution is affected.” Apply this procedure: Open before entry, compare its identity information and avoid reopening by relative name accidentally. The expected mechanism is: The handle remains attached to the file opened earlier because changing cwd does not rewrite an existing descriptor. For the homework file sorter, add one near-miss that exposes expecting an open handle to start reading a same-named file in the new directory. 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 export. Transfer the rule using relative CSV inputs and an absolute archive destination. 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 “An already-open file descriptor continues to refer to the same file when cwd changes; only later relative path resolution is affected.” Apply this procedure: Open before entry, compare its identity information and avoid reopening by relative name accidentally. The expected mechanism is: The handle remains attached to the file opened earlier because changing cwd does not rewrite an existing descriptor. For the library export, add one near-miss that exposes expecting an open handle to start reading a same-named file in the new directory. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Diagnostic route

  • Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
  • Boundary check: create the smallest input that triggers expecting an open handle to start reading a same-named file in the new directory.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Open before entry, compare its identity information and avoid reopening by relative name accidentally.” 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 contextlib.chdir syntax. For this chapter, useful prompts are: “What did you expect from Existing file handles do not retarget?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing expecting an open handle to start reading a same-named file in the new directory be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny homework file sorter with a disposable folder of draft answers and reviewed answers. Include one ordinary case, one boundary and one deliberate failure caused by expecting an open handle to start reading a same-named file in the new directory. 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: An already-open file descriptor continues to refer to the same file when cwd changes; only later relative path resolution is affected. It shows a trace, not only a final value. The ordinary case should demonstrate “The handle remains attached to the file opened earlier because changing cwd does not rewrite an existing descriptor.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Open before entry, compare its identity information and avoid reopening by relative name accidentally. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Existing file handles do not retarget, separate the documented Python contextlib.chdir 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. Subprocesses inherit cwd unless told otherwise

Back to contents

A child process normally starts with the parent process current directory, but subprocess APIs can accept an explicit cwd argument. 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 parent globally just to launch one command in another folder. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Pass cwd=destination to subprocess.run and leave the parent directory unchanged.

For the Subprocesses inherit cwd unless told otherwise chapter on Python contextlib.chdir, 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 parent globally just to launch one command in another folder. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

import subprocess
subprocess.run(['pwd'],cwd='/tmp',check=True)

Explained result. The child runs in /tmp while the Python process can remain in its original directory. 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: homework file sorter. Stress-test the rule using a disposable folder of draft answers and reviewed answers. 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 child process normally starts with the parent process current directory, but subprocess APIs can accept an explicit cwd argument.” Apply this procedure: Pass cwd=destination to subprocess.run and leave the parent directory unchanged. The expected mechanism is: The child runs in /tmp while the Python process can remain in its original directory. For the homework file sorter, add one near-miss that exposes changing the parent globally just to launch one command in another folder. 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 export. Explain the rule using relative CSV inputs and an absolute archive destination. 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 child process normally starts with the parent process current directory, but subprocess APIs can accept an explicit cwd argument.” Apply this procedure: Pass cwd=destination to subprocess.run and leave the parent directory unchanged. The expected mechanism is: The child runs in /tmp while the Python process can remain in its original directory. For the library export, add one near-miss that exposes changing the parent globally just to launch one command in another folder. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: CCA registration tool. Transfer the rule using configuration files and generated attendance sheets. 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 child process normally starts with the parent process current directory, but subprocess APIs can accept an explicit cwd argument.” Apply this procedure: Pass cwd=destination to subprocess.run and leave the parent directory unchanged. The expected mechanism is: The child runs in /tmp while the Python process can remain in its original directory. For the CCA registration tool, add one near-miss that exposes changing the parent globally just to launch one command in another folder. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: science-data script. Predict the rule using a temporary run directory with readings and charts. 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 child process normally starts with the parent process current directory, but subprocess APIs can accept an explicit cwd argument.” Apply this procedure: Pass cwd=destination to subprocess.run and leave the parent directory unchanged. The expected mechanism is: The child runs in /tmp while the Python process can remain in its original directory. For the science-data script, add one near-miss that exposes changing the parent globally just to launch one command in another folder. 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 parent globally just to launch one command in another folder.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Pass cwd=destination to subprocess.run and leave the parent directory unchanged.” 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 contextlib.chdir syntax. For this chapter, useful prompts are: “What did you expect from Subprocesses inherit cwd unless told otherwise?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing changing the parent globally just to launch one command in another folder be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny library export with relative CSV inputs and an absolute archive destination. Include one ordinary case, one boundary and one deliberate failure caused by changing the parent globally just to launch one command in another folder. 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 child process normally starts with the parent process current directory, but subprocess APIs can accept an explicit cwd argument. It shows a trace, not only a final value. The ordinary case should demonstrate “The child runs in /tmp while the Python process can remain in its original directory.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Pass cwd=destination to subprocess.run and leave the parent directory unchanged. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Subprocesses inherit cwd unless told otherwise, separate the documented Python contextlib.chdir 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. Imports and resource lookup deserve explicit contracts

Back to contents

Changing cwd can affect ad-hoc relative resource reads, while import behaviour also depends on sys.path and execution mode rather than cwd alone. 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 chdir as a vague fix for any module or resource not found. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Use package-resource APIs, explicit configuration paths and a recorded import path instead of guessing.

For the Imports and resource lookup deserve explicit contracts chapter on Python contextlib.chdir, 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 chdir as a vague fix for any module or resource not found. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from importlib.resources import files
# data = files('my_package').joinpath('data.json')

Explained result. Package resources are addressed through the package contract rather than an ambient process directory. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: CCA registration tool. Explain the rule using configuration files and generated attendance sheets. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “Changing cwd can affect ad-hoc relative resource reads, while import behaviour also depends on sys.path and execution mode rather than cwd alone.” Apply this procedure: Use package-resource APIs, explicit configuration paths and a recorded import path instead of guessing. The expected mechanism is: Package resources are addressed through the package contract rather than an ambient process directory. For the CCA registration tool, add one near-miss that exposes using chdir as a vague fix for any module or resource not found. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: science-data script. Transfer the rule using a temporary run directory with readings and charts. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “Changing cwd can affect ad-hoc relative resource reads, while import behaviour also depends on sys.path and execution mode rather than cwd alone.” Apply this procedure: Use package-resource APIs, explicit configuration paths and a recorded import path instead of guessing. The expected mechanism is: Package resources are addressed through the package contract rather than an ambient process directory. For the science-data script, add one near-miss that exposes using chdir as a vague fix for any module or resource not found. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: revision-note builder. Predict the rule using Markdown sources and an output folder. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “Changing cwd can affect ad-hoc relative resource reads, while import behaviour also depends on sys.path and execution mode rather than cwd alone.” Apply this procedure: Use package-resource APIs, explicit configuration paths and a recorded import path instead of guessing. The expected mechanism is: Package resources are addressed through the package contract rather than an ambient process directory. For the revision-note builder, add one near-miss that exposes using chdir as a vague fix for any module or resource not found. 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: photo-index exercise. Contrast the rule using sample image names and a generated catalogue. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “Changing cwd can affect ad-hoc relative resource reads, while import behaviour also depends on sys.path and execution mode rather than cwd alone.” Apply this procedure: Use package-resource APIs, explicit configuration paths and a recorded import path instead of guessing. The expected mechanism is: Package resources are addressed through the package contract rather than an ambient process directory. For the photo-index exercise, add one near-miss that exposes using chdir as a vague fix for any module or resource not found. 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 chdir as a vague fix for any module or resource not found.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Use package-resource APIs, explicit configuration paths and a recorded import path instead of guessing.” 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 contextlib.chdir syntax. For this chapter, useful prompts are: “What did you expect from Imports and resource lookup deserve explicit contracts?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing using chdir as a vague fix for any module or resource not found be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny CCA registration tool with configuration files and generated attendance sheets. Include one ordinary case, one boundary and one deliberate failure caused by using chdir as a vague fix for any module or resource not found. Predict each result before using a tool, then report the first point where observation differs from prediction.

Answer guide. A strong response starts with the rule: Changing cwd can affect ad-hoc relative resource reads, while import behaviour also depends on sys.path and execution mode rather than cwd alone. It shows a trace, not only a final value. The ordinary case should demonstrate “Package resources are addressed through the package contract rather than an ambient process directory.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Use package-resource APIs, explicit configuration paths and a recorded import path instead of guessing. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Imports and resource lookup deserve explicit contracts, separate the documented Python contextlib.chdir 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. Restoration itself can fail

Back to contents

Restoration requires the saved directory to remain reachable; deleting or invalidating it during the block can make the exit operation fail. 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 restoration as an unconditional transaction regardless of filesystem changes. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Never remove the saved working directory; keep destructive experiments in a child directory.

For the Restoration itself can fail chapter on Python contextlib.chdir, 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 restoration as an unconditional transaction regardless of filesystem changes. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

# Dangerous: enter child, then remove or unmount the saved parent
# Safe: create disposable work beneath a stable base

Explained result. The context manager attempts restoration, but the operating system can reject chdir when the original location no longer exists or is inaccessible. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: revision-note builder. Transfer the rule using Markdown sources and an output folder. 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 “Restoration requires the saved directory to remain reachable; deleting or invalidating it during the block can make the exit operation fail.” Apply this procedure: Never remove the saved working directory; keep destructive experiments in a child directory. The expected mechanism is: The context manager attempts restoration, but the operating system can reject chdir when the original location no longer exists or is inaccessible. For the revision-note builder, add one near-miss that exposes treating restoration as an unconditional transaction regardless of filesystem changes. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: photo-index exercise. Predict the rule using sample image names and a generated catalogue. 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 “Restoration requires the saved directory to remain reachable; deleting or invalidating it during the block can make the exit operation fail.” Apply this procedure: Never remove the saved working directory; keep destructive experiments in a child directory. The expected mechanism is: The context manager attempts restoration, but the operating system can reject chdir when the original location no longer exists or is inaccessible. For the photo-index exercise, add one near-miss that exposes treating restoration as an unconditional transaction regardless of filesystem changes. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: budget practice app. Contrast the rule using relative data files and an exported summary. 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 “Restoration requires the saved directory to remain reachable; deleting or invalidating it during the block can make the exit operation fail.” Apply this procedure: Never remove the saved working directory; keep destructive experiments in a child directory. The expected mechanism is: The context manager attempts restoration, but the operating system can reject chdir when the original location no longer exists or is inaccessible. For the budget practice app, add one near-miss that exposes treating restoration as an unconditional transaction regardless of filesystem changes. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: project build rehearsal. Stress-test the rule using source folders, subprocesses and test artefacts. 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 “Restoration requires the saved directory to remain reachable; deleting or invalidating it during the block can make the exit operation fail.” Apply this procedure: Never remove the saved working directory; keep destructive experiments in a child directory. The expected mechanism is: The context manager attempts restoration, but the operating system can reject chdir when the original location no longer exists or is inaccessible. For the project build rehearsal, add one near-miss that exposes treating restoration as an unconditional transaction regardless of filesystem changes. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Diagnostic route

  • Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
  • Boundary check: create the smallest input that triggers treating restoration as an unconditional transaction regardless of filesystem changes.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Never remove the saved working directory; keep destructive experiments in a child directory.” 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 contextlib.chdir syntax. For this chapter, useful prompts are: “What did you expect from Restoration itself can fail?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing treating restoration as an unconditional transaction regardless of filesystem changes be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny science-data script with a temporary run directory with readings and charts. Include one ordinary case, one boundary and one deliberate failure caused by treating restoration as an unconditional transaction regardless of filesystem changes. Predict each result before using a tool, then report the first point where observation differs from prediction.

Answer guide. A strong response starts with the rule: Restoration requires the saved directory to remain reachable; deleting or invalidating it during the block can make the exit operation fail. It shows a trace, not only a final value. The ordinary case should demonstrate “The context manager attempts restoration, but the operating system can reject chdir when the original location no longer exists or is inaccessible.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Never remove the saved working directory; keep destructive experiments in a child directory. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Restoration itself can fail, separate the documented Python contextlib.chdir 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. chdir is not a sandbox

Back to contents

Changing cwd does not restrict absolute paths, permissions, network access or process capabilities. 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 presenting the temporary directory as a security boundary. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Use operating-system permissions or an actual sandbox for isolation; treat chdir only as path-resolution state.

For the chdir is not a sandbox chapter on Python contextlib.chdir, 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 presenting the temporary directory as a security boundary. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

with chdir('/tmp'):
    path=Path('/etc/hosts')
    print(path.is_absolute())

Explained result. The absolute path remains absolute and is not confined beneath /tmp. 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: budget practice app. Predict the rule using relative data files and an exported summary. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “Changing cwd does not restrict absolute paths, permissions, network access or process capabilities.” Apply this procedure: Use operating-system permissions or an actual sandbox for isolation; treat chdir only as path-resolution state. The expected mechanism is: The absolute path remains absolute and is not confined beneath /tmp. For the budget practice app, add one near-miss that exposes presenting the temporary directory as a security boundary. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: project build rehearsal. Contrast the rule using source folders, subprocesses and test artefacts. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “Changing cwd does not restrict absolute paths, permissions, network access or process capabilities.” Apply this procedure: Use operating-system permissions or an actual sandbox for isolation; treat chdir only as path-resolution state. The expected mechanism is: The absolute path remains absolute and is not confined beneath /tmp. For the project build rehearsal, add one near-miss that exposes presenting the temporary directory as a security boundary. 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: homework file sorter. Stress-test the rule using a disposable folder of draft answers and reviewed answers. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “Changing cwd does not restrict absolute paths, permissions, network access or process capabilities.” Apply this procedure: Use operating-system permissions or an actual sandbox for isolation; treat chdir only as path-resolution state. The expected mechanism is: The absolute path remains absolute and is not confined beneath /tmp. For the homework file sorter, add one near-miss that exposes presenting the temporary directory as a security boundary. 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 export. Explain the rule using relative CSV inputs and an absolute archive destination. State the input grain or object graph, the chapter boundary and the intended output before choosing syntax. Change only one variable, so a wrong prediction has a single plausible cause.

Reasoned route. Begin with “Changing cwd does not restrict absolute paths, permissions, network access or process capabilities.” Apply this procedure: Use operating-system permissions or an actual sandbox for isolation; treat chdir only as path-resolution state. The expected mechanism is: The absolute path remains absolute and is not confined beneath /tmp. For the library export, add one near-miss that exposes presenting the temporary directory as a security boundary. 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 presenting the temporary directory as a security boundary.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Use operating-system permissions or an actual sandbox for isolation; treat chdir only as path-resolution state.” 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 contextlib.chdir syntax. For this chapter, useful prompts are: “What did you expect from chdir is not a sandbox?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing presenting the temporary directory as a security boundary be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny revision-note builder with Markdown sources and an output folder. Include one ordinary case, one boundary and one deliberate failure caused by presenting the temporary directory as a security boundary. Predict each result before using a tool, then report the first point where observation differs from prediction.

Answer guide. A strong response starts with the rule: Changing cwd does not restrict absolute paths, permissions, network access or process capabilities. It shows a trace, not only a final value. The ordinary case should demonstrate “The absolute path remains absolute and is not confined beneath /tmp.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Use operating-system permissions or an actual sandbox for isolation; treat chdir only as path-resolution state. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For chdir is not a sandbox, separate the documented Python contextlib.chdir 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. A manual try-finally has the same essential burden

Back to contents

Saving cwd, changing it and restoring in finally explains the helper’s mechanism, but hand-written versions are easier to get wrong. 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 repeated restoration code with inconsistent exception handling. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Use contextlib.chdir for linear single-threaded scripts and show the equivalent model once in tests.

For the A manual try-finally has the same essential burden chapter on Python contextlib.chdir, 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 repeated restoration code with inconsistent exception handling. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

old=os.getcwd()
try:
    os.chdir(dest)
finally:
    os.chdir(old)

Explained result. The structure makes restoration explicit; contextlib.chdir packages the same linear responsibility. 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: homework file sorter. Contrast the rule using a disposable folder of draft answers and reviewed answers. 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 “Saving cwd, changing it and restoring in finally explains the helper’s mechanism, but hand-written versions are easier to get wrong.” Apply this procedure: Use contextlib.chdir for linear single-threaded scripts and show the equivalent model once in tests. The expected mechanism is: The structure makes restoration explicit; contextlib.chdir packages the same linear responsibility. For the homework file sorter, add one near-miss that exposes writing repeated restoration code with inconsistent exception handling. 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 export. Stress-test the rule using relative CSV inputs and an absolute archive destination. 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 “Saving cwd, changing it and restoring in finally explains the helper’s mechanism, but hand-written versions are easier to get wrong.” Apply this procedure: Use contextlib.chdir for linear single-threaded scripts and show the equivalent model once in tests. The expected mechanism is: The structure makes restoration explicit; contextlib.chdir packages the same linear responsibility. For the library export, add one near-miss that exposes writing repeated restoration code with inconsistent exception handling. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: CCA registration tool. Explain the rule using configuration files and generated attendance sheets. 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 “Saving cwd, changing it and restoring in finally explains the helper’s mechanism, but hand-written versions are easier to get wrong.” Apply this procedure: Use contextlib.chdir for linear single-threaded scripts and show the equivalent model once in tests. The expected mechanism is: The structure makes restoration explicit; contextlib.chdir packages the same linear responsibility. For the CCA registration tool, add one near-miss that exposes writing repeated restoration code with inconsistent exception handling. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: science-data script. Transfer the rule using a temporary run directory with readings and charts. 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 “Saving cwd, changing it and restoring in finally explains the helper’s mechanism, but hand-written versions are easier to get wrong.” Apply this procedure: Use contextlib.chdir for linear single-threaded scripts and show the equivalent model once in tests. The expected mechanism is: The structure makes restoration explicit; contextlib.chdir packages the same linear responsibility. For the science-data script, add one near-miss that exposes writing repeated restoration code with inconsistent exception handling. 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 repeated restoration code with inconsistent exception handling.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Use contextlib.chdir for linear single-threaded scripts and show the equivalent model once in tests.” 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 contextlib.chdir syntax. For this chapter, useful prompts are: “What did you expect from A manual try-finally has the same essential burden?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing writing repeated restoration code with inconsistent exception handling be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny photo-index exercise with sample image names and a generated catalogue. Include one ordinary case, one boundary and one deliberate failure caused by writing repeated restoration code with inconsistent exception handling. 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: Saving cwd, changing it and restoring in finally explains the helper’s mechanism, but hand-written versions are easier to get wrong. It shows a trace, not only a final value. The ordinary case should demonstrate “The structure makes restoration explicit; contextlib.chdir packages the same linear responsibility.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Use contextlib.chdir for linear single-threaded scripts and show the equivalent model once in tests. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For A manual try-finally has the same essential burden, separate the documented Python contextlib.chdir 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. TemporaryDirectory pairs with chdir but owns a different job

Back to contents

TemporaryDirectory manages a directory lifetime, while chdir only changes path resolution and restores cwd. 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 exiting TemporaryDirectory while still using it as the current directory. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Nest chdir inside the temporary-directory lifetime so cwd is restored before cleanup.

For the TemporaryDirectory pairs with chdir but owns a different job chapter on Python contextlib.chdir, 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 exiting TemporaryDirectory while still using it as the current directory. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

from tempfile import TemporaryDirectory
from contextlib import chdir
with TemporaryDirectory() as d:
    with chdir(d):
        pass

Explained result. The inner block restores cwd before the outer manager removes the temporary directory. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: CCA registration tool. Stress-test the rule using configuration files and generated attendance sheets. 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 “TemporaryDirectory manages a directory lifetime, while chdir only changes path resolution and restores cwd.” Apply this procedure: Nest chdir inside the temporary-directory lifetime so cwd is restored before cleanup. The expected mechanism is: The inner block restores cwd before the outer manager removes the temporary directory. For the CCA registration tool, add one near-miss that exposes exiting TemporaryDirectory while still using it as the current directory. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: science-data script. Explain the rule using a temporary run directory with readings and charts. 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 “TemporaryDirectory manages a directory lifetime, while chdir only changes path resolution and restores cwd.” Apply this procedure: Nest chdir inside the temporary-directory lifetime so cwd is restored before cleanup. The expected mechanism is: The inner block restores cwd before the outer manager removes the temporary directory. For the science-data script, add one near-miss that exposes exiting TemporaryDirectory while still using it as the current directory. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 3: revision-note builder. Transfer the rule using Markdown sources and an output folder. 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 “TemporaryDirectory manages a directory lifetime, while chdir only changes path resolution and restores cwd.” Apply this procedure: Nest chdir inside the temporary-directory lifetime so cwd is restored before cleanup. The expected mechanism is: The inner block restores cwd before the outer manager removes the temporary directory. For the revision-note builder, add one near-miss that exposes exiting TemporaryDirectory while still using it as the current directory. 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: photo-index exercise. Predict the rule using sample image names and a generated catalogue. 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 “TemporaryDirectory manages a directory lifetime, while chdir only changes path resolution and restores cwd.” Apply this procedure: Nest chdir inside the temporary-directory lifetime so cwd is restored before cleanup. The expected mechanism is: The inner block restores cwd before the outer manager removes the temporary directory. For the photo-index exercise, add one near-miss that exposes exiting TemporaryDirectory while still using it as the current directory. 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 exiting TemporaryDirectory while still using it as the current directory.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Nest chdir inside the temporary-directory lifetime so cwd is restored before cleanup.” 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 contextlib.chdir syntax. For this chapter, useful prompts are: “What did you expect from TemporaryDirectory pairs with chdir but owns a different job?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing exiting TemporaryDirectory while still using it as the current directory be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny budget practice app with relative data files and an exported summary. Include one ordinary case, one boundary and one deliberate failure caused by exiting TemporaryDirectory while still using it as the current directory. 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: TemporaryDirectory manages a directory lifetime, while chdir only changes path resolution and restores cwd. It shows a trace, not only a final value. The ordinary case should demonstrate “The inner block restores cwd before the outer manager removes the temporary directory.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Nest chdir inside the temporary-directory lifetime so cwd is restored before cleanup. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For TemporaryDirectory pairs with chdir but owns a different job, separate the documented Python contextlib.chdir 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. Tests must restore state even on failure

Back to contents

A test that changes cwd can contaminate every later test in the same process unless cleanup is guaranteed. 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 os.chdir at test start and relying on the final assertion to restore it. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. Use tmp_path plus chdir in a with block, and assert cwd after the block.

For the Tests must restore state even on failure chapter on Python contextlib.chdir, 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 os.chdir at test start and relying on the final assertion to restore it. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

def test_relative_output(tmp_path):
    before=Path.cwd()
    with chdir(tmp_path):
        assert Path.cwd()==tmp_path
    assert Path.cwd()==before

Explained result. The test keeps the global mutation scoped even when an assertion inside the block fails. Check the boundary as well as the happy path: ask what happens with an empty input, a duplicate or tied value, an unsupported type, a missing path, a NULL, or a second reference to the same object. Only the relevant boundary should be kept; the list is a prompt for judgment, not a demand to force every case into every example.

Four purposeful transfer cases

Case 1: revision-note builder. Explain the rule using Markdown sources and an output folder. 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 test that changes cwd can contaminate every later test in the same process unless cleanup is guaranteed.” Apply this procedure: Use tmp_path plus chdir in a with block, and assert cwd after the block. The expected mechanism is: The test keeps the global mutation scoped even when an assertion inside the block fails. For the revision-note builder, add one near-miss that exposes calling os.chdir at test start and relying on the final assertion to restore it. 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: photo-index exercise. Transfer the rule using sample image names and a generated catalogue. 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 test that changes cwd can contaminate every later test in the same process unless cleanup is guaranteed.” Apply this procedure: Use tmp_path plus chdir in a with block, and assert cwd after the block. The expected mechanism is: The test keeps the global mutation scoped even when an assertion inside the block fails. For the photo-index exercise, add one near-miss that exposes calling os.chdir at test start and relying on the final assertion to restore it. 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: budget practice app. Predict the rule using relative data files and an exported summary. 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 test that changes cwd can contaminate every later test in the same process unless cleanup is guaranteed.” Apply this procedure: Use tmp_path plus chdir in a with block, and assert cwd after the block. The expected mechanism is: The test keeps the global mutation scoped even when an assertion inside the block fails. For the budget practice app, add one near-miss that exposes calling os.chdir at test start and relying on the final assertion to restore it. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 4: project build rehearsal. Contrast the rule using source folders, subprocesses and test artefacts. 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 test that changes cwd can contaminate every later test in the same process unless cleanup is guaranteed.” Apply this procedure: Use tmp_path plus chdir in a with block, and assert cwd after the block. The expected mechanism is: The test keeps the global mutation scoped even when an assertion inside the block fails. For the project build rehearsal, add one near-miss that exposes calling os.chdir at test start and relying on the final assertion to restore it. 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 os.chdir at test start and relying on the final assertion to restore it.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “Use tmp_path plus chdir in a with block, and assert cwd after the 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 contextlib.chdir syntax. For this chapter, useful prompts are: “What did you expect from Tests must restore state even on failure?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing calling os.chdir at test start and relying on the final assertion to restore it be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny project build rehearsal with source folders, subprocesses and test artefacts. Include one ordinary case, one boundary and one deliberate failure caused by calling os.chdir at test start and relying on the final assertion to restore it. 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 test that changes cwd can contaminate every later test in the same process unless cleanup is guaranteed. It shows a trace, not only a final value. The ordinary case should demonstrate “The test keeps the global mutation scoped even when an assertion inside the block fails.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: Use tmp_path plus chdir in a with block, and assert cwd after the block. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Tests must restore state even on failure, separate the documented Python contextlib.chdir 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 explicit paths for reusable code

Back to contents

contextlib.chdir suits controlled, linear utility scripts; reusable libraries and concurrent applications are clearer when paths or cwd parameters are explicit. Treat that sentence as a testable model. A secure learner can point to the relevant input, name the operation, describe the resulting state and identify one observation that would prove the model incomplete.

The high-value mistake in this chapter is choosing global state because relative examples are shorter. It matters because the output may look reasonable while the ownership, ordering, identity or safety rule is wrong. List every consumer of cwd, every possible suspension point and the safer explicit-path alternative.

For the Choose explicit paths for reusable code chapter on Python contextlib.chdir, use a two-column trace during a short Punggol home session. On the left, write the predicted state for this exact mechanism before the tool runs. On the right, record the observation that bears on choosing global state because relative examples are shorter. Explain the earliest difference with one causal sentence, then repeat only the smallest changed case.

Core worked example

def build(source_dir: Path, output_dir: Path):
    ...

Explained result. Explicit parameters make ownership visible and allow concurrent calls without competing over a process-wide directory. 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: budget practice app. Transfer the rule using relative data files and an exported summary. 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 “contextlib.chdir suits controlled, linear utility scripts; reusable libraries and concurrent applications are clearer when paths or cwd parameters are explicit.” Apply this procedure: List every consumer of cwd, every possible suspension point and the safer explicit-path alternative. The expected mechanism is: Explicit parameters make ownership visible and allow concurrent calls without competing over a process-wide directory. For the budget practice app, add one near-miss that exposes choosing global state because relative examples are shorter. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Case 2: project build rehearsal. Predict the rule using source folders, subprocesses and test artefacts. 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 “contextlib.chdir suits controlled, linear utility scripts; reusable libraries and concurrent applications are clearer when paths or cwd parameters are explicit.” Apply this procedure: List every consumer of cwd, every possible suspension point and the safer explicit-path alternative. The expected mechanism is: Explicit parameters make ownership visible and allow concurrent calls without competing over a process-wide directory. For the project build rehearsal, add one near-miss that exposes choosing global state because relative examples are shorter. 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: homework file sorter. Contrast the rule using a disposable folder of draft answers and reviewed answers. 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 “contextlib.chdir suits controlled, linear utility scripts; reusable libraries and concurrent applications are clearer when paths or cwd parameters are explicit.” Apply this procedure: List every consumer of cwd, every possible suspension point and the safer explicit-path alternative. The expected mechanism is: Explicit parameters make ownership visible and allow concurrent calls without competing over a process-wide directory. For the homework file sorter, add one near-miss that exposes choosing global state because relative examples are shorter. 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 export. Stress-test the rule using relative CSV inputs and an absolute archive destination. 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 “contextlib.chdir suits controlled, linear utility scripts; reusable libraries and concurrent applications are clearer when paths or cwd parameters are explicit.” Apply this procedure: List every consumer of cwd, every possible suspension point and the safer explicit-path alternative. The expected mechanism is: Explicit parameters make ownership visible and allow concurrent calls without competing over a process-wide directory. For the library export, add one near-miss that exposes choosing global state because relative examples are shorter. The answer is complete only when it says why the near-miss fails and how the corrected model transfers to a different project without relying on the original variable names.

Diagnostic route

  • Model check: ask the learner to draw or list the exact rows, fields, references, paths or states involved.
  • Boundary check: create the smallest input that triggers choosing global state because relative examples are shorter.
  • Evidence check: separate a printed value from identity, ordering, ownership, type or repository state.
  • Repair check: use the reversible procedure “List every consumer of cwd, every possible suspension point and the safer explicit-path alternative.” 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 contextlib.chdir syntax. For this chapter, useful prompts are: “What did you expect from Choose explicit paths for reusable code?”, “Which state changed first?”, “What evidence tests that prediction?”, and “Can the case exposing choosing global state because relative examples are shorter be made smaller?” The learner, not the parent, should supply the technical explanation.

Practice with an explained answer

Question. Build a tiny homework file sorter with a disposable folder of draft answers and reviewed answers. Include one ordinary case, one boundary and one deliberate failure caused by choosing global state because relative examples are shorter. 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: contextlib.chdir suits controlled, linear utility scripts; reusable libraries and concurrent applications are clearer when paths or cwd parameters are explicit. It shows a trace, not only a final value. The ordinary case should demonstrate “Explicit parameters make ownership visible and allow concurrent calls without competing over a process-wide directory.” The boundary must exercise the same mechanism at an edge, and the deliberate failure must be repaired with: List every consumer of cwd, every possible suspension point and the safer explicit-path alternative. Other data choices are valid when the evidence supports the same causal chain.

Decision and transfer

For Choose explicit paths for reusable code, separate the documented Python contextlib.chdir 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. homework file sorter: model, boundary and recovery

Create a small homework file sorter using a disposable folder of draft answers and reviewed answers. Combine “The context manager changes one process-wide directory” 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: Entering contextlib.chdir(path) calls the operating-system directory change and leaving restores the directory that was current before entry. Apply: Print Path.cwd() before, inside and after a block in a disposable directory. Verify: Inside the block the process directory is /tmp; after normal exit the original directory is restored. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.

2. library export: model, boundary and recovery

Create a small library export using relative CSV inputs and an absolute archive destination. Combine “A relative destination is resolved at entry” 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 relative path is interpreted from the current working directory at the moment the context is entered. Apply: Capture an absolute base Path before entry and construct destinations from that base. Verify: The explicit absolute destination remains anchored to the intended base even if surrounding code later changes directory. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.

3. CCA registration tool: model, boundary and recovery

Create a small CCA registration tool using configuration files and generated attendance sheets. Combine “Nested use is reentrant” 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: Each entry saves the directory current at that level, so an inner block restores to the outer temporary directory before the outer block restores to the start. Apply: Print a three-row trace for start, outer, inner, outer-restored and final-restored states. Verify: The inner exit returns to /tmp, and the outer exit later returns to the directory that preceded the outer block. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.

4. science-data script: model, boundary and recovery

Create a small science-data script using a temporary run directory with readings and charts. Combine “Generators make the lifetime non-linear” 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: Yielding from inside the block suspends execution while leaving the process directory changed until iteration resumes or closes. Apply: Materialise required values before yielding, or remove the directory change by using absolute paths. Verify: After the first next call, the generator is suspended and the temporary cwd remains 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.

5. revision-note builder: model, boundary and recovery

Create a small revision-note builder using Markdown sources and an output folder. Combine “Subprocesses inherit cwd unless told otherwise” 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 child process normally starts with the parent process current directory, but subprocess APIs can accept an explicit cwd argument. Apply: Pass cwd=destination to subprocess.run and leave the parent directory unchanged. Verify: The child runs in /tmp while the Python process can remain in its original directory. 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. photo-index exercise: model, boundary and recovery

Create a small photo-index exercise using sample image names and a generated catalogue. Combine “chdir is not a sandbox” 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: Changing cwd does not restrict absolute paths, permissions, network access or process capabilities. Apply: Use operating-system permissions or an actual sandbox for isolation; treat chdir only as path-resolution state. Verify: The absolute path remains absolute and is not confined beneath /tmp. 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. budget practice app: model, boundary and recovery

Create a small budget practice app using relative data files and an exported summary. Combine “Tests must restore state even on failure” 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 test that changes cwd can contaminate every later test in the same process unless cleanup is guaranteed. Apply: Use tmp_path plus chdir in a with block, and assert cwd after the block. Verify: The test keeps the global mutation scoped even when an assertion inside the block fails. Then add a second chapter whose boundary could change the outcome. A complete solution contains the input model, a trace, observed evidence, a correction and one transfer statement. The exact data may differ; the causal chain must be checkable.

8. project build rehearsal: model, boundary and recovery

Create a small project build rehearsal using source folders, subprocesses and test artefacts. Combine “The as-target is None” 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: contextlib.chdir manages state but its __enter__ result is None, so with chdir(path) as value does not bind the destination Path. Apply: Keep the destination in an explicit Path variable and inspect cwd separately. Verify: entered is None while Path.cwd() reports the temporary directory. 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 的更多信息

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

继续阅读