Pylerno
English

TaskFlow capstone

Read and extend a modular, tested application without introducing OOP.

On this page

The concept

TaskFlow combines a pure domain layer, a JSON storage layer, and a command-line boundary. domain.py owns title and task rules. storage.py validates an explicit schema, keeps a monotonically increasing next_id, and replaces the data file using a completed temporary file. cli.py handles arguments, output, and exit codes.

The application is designed for one user and one writer at a time. Atomic file replacement prevents exposing a partially written file, but does not coordinate simultaneous read-modify-write operations by multiple processes. SQLite transactions would be a suitable next step for that requirement. The lesson runner exercises the real package using disposable data.

Worked example

Extract the example files. From the python_from_zero directory, run the following command in a terminal. On Windows, use py in place of python3.

sh
python3 09_projects/72_taskflow_capstone/lesson.py
python
import subprocess
import sys
from pathlib import Path
from tempfile import TemporaryDirectory


def main():
    project = Path(__file__).resolve().parent / "app"
    with TemporaryDirectory(prefix="taskflow_demo_") as temporary:
        data = Path(temporary) / "tasks.json"
        for arguments in [
            ["add", "Learn functions"],
            ["add", "Write meaningful tests"],
            ["done", "1"],
            ["list"],
        ]:
            result = subprocess.run(
                [sys.executable, "-m", "taskflow", "--data", str(data), *arguments],
                cwd=project,
                capture_output=True,
                text=True,
                check=True,
                timeout=10,
            )
            print(result.stdout, end="")


if __name__ == "__main__":
    main()

Trace the result

  1. The demo locates the project from its own file location rather than assuming a working directory.
  2. Each subprocess invokes python -m taskflow with the same temporary data path.
  3. The sequence adds two tasks, completes the first, and lists both; all temporary data is removed afterward.
text
Added task 1.
Added task 2.
Completed task 1.
1. [x] Learn functions
2. [ ] Write meaningful tests
Line-by-line walkthrough

Line 1: import subprocess

Load subprocess (running a child process with controlled arguments). Importing makes these names available; it is not a call to every function in the module.

Line 2: import sys

Load sys (interpreter information and command-line arguments). Importing makes these names available; it is not a call to every function in the module.

Line 3: from pathlib import Path

Import Path from pathlib. This supplies filesystem path values. The caller can now use the imported names directly.

Line 4: from tempfile import TemporaryDirectory

Import TemporaryDirectory from tempfile. This supplies temporary files and directories. The caller can now use the imported names directly.

Lines 7–25: def main():

Define the function main with input names no parameters. Definition stores the operation rather than executing its body. An ordinary call executes a normal function; a coroutine runs when awaited/scheduled, and a generator advances when consumed. Decorators can provide a context-manager or wrapper interface. Indented statements below belong to this operation.

Line 8: project = Path(__file__).resolve().parent / "app"

Evaluate Path(__file__).resolve().parent / 'app', then bind or update project with the result. Assignment itself does not imply a deep copy.

Lines 9–25: with TemporaryDirectory(prefix="taskflow_demo_") as temporary:

Enter the listed context manager(s), run the indented block, and leave each context afterward. The manager defines the cleanup/commit behavior; a database transaction and a file lifetime are not identical contracts.

Line 10: data = Path(temporary) / "tasks.json"

Evaluate Path(temporary) / 'tasks.json', then bind or update data with the result. Assignment itself does not imply a deep copy.

Lines 11–25: for arguments in [

Obtain each item from [['add', 'Learn functions'], ['add', 'Write meaningful tests'], ['done', '1'], ['list']] and bind it to arguments before executing the body. A tuple-shaped target unpacks that item. A loop else, if present, runs only when completion does not use break.

Lines 17–24: result = subprocess.run(

Evaluate subprocess.run([sys.executable, '-m', 'taskflow', '--data', str(data), *arguments], cwd=project, capture_output=True, text=True, check=True, timeout=10), then bind or update result with the result. The call finishes before its return value is bound; a failed call does not produce a successful assignment. Assignment itself does not imply a deep copy.

Line 25: print(result.stdout, end="")

Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.

Lines 28–29: if __name__ == "__main__":

Enter the program entry point only during direct execution. Importing this module still creates definitions but does not run this guarded workflow.

Line 29: main()

Call main with the displayed arguments. This call may have an effect even when its return value is not assigned.

Common mistake

Atomic replacement is not a concurrency lock. Also, never convert corrupt stored JSON into an empty database and overwrite it silently.

Run TaskFlow

From the extracted examples, enter 09_projects/72_taskflow_capstone/app.

From this app directory:

sh
python3 -m taskflow --help
python3 -m taskflow --data ./practice.json add "Learn Python"
python3 -m taskflow --data ./practice.json add "Write tests"
python3 -m taskflow --data ./practice.json list
python3 -m taskflow --data ./practice.json done 1
python3 -m taskflow --data ./practice.json list --status done
python3 -m taskflow --data ./practice.json list --json
python3 -m taskflow --data ./practice.json remove 1

Place --data before the subcommand. Without it, tasks.json is relative to the current working directory. list does not create a missing file; mutations save data. The lesson.py wrapper uses a temporary path instead, so its demonstration leaves no permanent task file.

Application structure

  1. domain.py: normalization, validated records, and new task lists without input mutation.
  2. storage.py: bounded loading, schema checks, and completed temporary-file replacement.
  3. cli.py: arguments, selected operations, result formatting, and controlled error output.
  4. main.py: turn the CLI's return status into a process exit status.
  5. tests: behavioral requirements, failure paths, and full process-level usage.

Check your understanding

Tasks have IDs 1 and 3 after a deletion. Which ID can be safely assigned next if next_id is 4?

Choose one answer

Search documentation

Share this page