Skip to main content
6 day streak
Skip to lesson
CareerPetalPython field guide
Loading progress...
Course contents
PYTHON FIELD GUIDE

Course contents 72 topics / 15 parts

Full course overviewOriginal coding practice / separate server checks

Essentials first, then internals and engineering trade-offs.

LESSON 50 / BUILDING AND SHIPPING

Package and ship a tested command-line tool

Turn a script into a project another developer can install and run.

IntermediateTutorial 14 min core+12 min deep divePython 3.11+ / 2026-10-27
Saved work unavailable

Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.

Before you start

Learners who can read small Python functions and want to apply the listed foundations.

Explore the connected curriculum and preparation map

Lesson content version 2026-10-27. Suggested core budget: 14 minutes; optional deep dive: 12 more minutes. These are reading/practice estimates, not a timed test.

Suggested preparation and repair routes

If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.

Actual runtime and local-lab boundaries

Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.

Packaging, shell arguments and project installation are local labs. Browser code cannot create a persistent installed command.

Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.

YOU WILL BE ABLE TO
  • Explain separate the command from the computation
  • Apply declare the project contract
  • Reason about dependencies and release safety
01

Separate the command from the computation

A command-line tool has a boundary that reads arguments and a core that computes results. Keep those responsibilities separate so each can be tested directly.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

A pure calculation can serve a terminal command, a web request or a test. It should not secretly read process-global arguments or print its only result.

Words you will see

CLI
A command-line interface controlled by argument text.
argv
The list of command arguments supplied to a parser.
Pure function
A function whose result follows its inputs without changing external state.

Text crosses a boundary

The fixture converts two argument strings into integers before summing. The total function works on numbers and returns a number. The final print is presentation, not the calculation's only interface. An empty numeric list sums to zero.

Separating these stages makes failures easier to locate. int can reject malformed text with ValueError; a later domain rule may reject negative minutes even though they are valid integers. Decide both contracts instead of treating parsing as complete validation.

Make the command testable

Pass an explicit list in parser tests instead of mutating sys.argv. Call the calculation directly in unit tests. Use an outer main function to translate expected user mistakes into documented diagnostic output and a nonzero exit status.

The browser can demonstrate explicit argument lists but is not a host shell or installed command. Actual entry-point invocation needs a host environment. A direct function test does not prove installation, process exit behavior or terminal integration.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. def total(minutes):

    Accept numeric input independently of the shell.

  2. argv = ["10", "15"]

    Supply fixed argument text for this fixture.

  3. minutes = [int(value) for value in argv]

    Build numbers without replacing the caller's strings.

  4. print(total(minutes))

    Display the returned calculation at the outer boundary.

Keep parsing, business logic and output formatting separate. A CLI should return useful exit codes and send diagnostics to stderr. Its core functions should be testable without launching a shell or parsing process-global arguments.

Conceptual command boundary

Conceptual reasoning steps for the original example, not a live trace of your edited Python.

  1. ParseConvert supplied argument strings and report syntax errors.
  2. ComputeApply domain rules and return a value.
  3. PresentWrite successful data to stdout and diagnostics to stderr.
Predict before you run

Does converting minutes change argv?

Keep computation independent of argument textPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Try no numbers.

Try: Change argv to [].

The pure sum returns zero; a production parser may separately require arguments.

Try malformed text.

Try: Change "15" to "later".

int raises ValueError instead of silently inventing minutes.

Before you move on

A test calls total([10, 15]) successfully. Has it proved that the installed command parses 10 and 15?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

No. It proves the calculation for numeric input. Test the parser with argument strings and separately test the installed command on a host.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
02

Declare the project contract

Project metadata declares how a distribution is built and what it installs. A console entry point maps a command name to an importable callable.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

A script working in a checkout may fail after installation if files, dependencies or entry points were never included in the distribution.

Words you will see

pyproject.toml
A project configuration file whose tables declare build and project metadata.
Wheel
A built Python distribution intended for installation.
Entry point
Metadata naming a callable used by an installed command.

Read declarations as data

tomllib reads the fixed TOML text into nested dictionaries. The project table supplies a name and a Python compatibility declaration. The project.scripts table maps study to study.cli:main: the module path before the colon and callable name after it.

This demonstrates metadata shape, not an installed package. The callable must actually exist in the built artifact. Declaring requires-python does not test every advertised interpreter; CI must exercise the support range or the declaration should be narrowed.

Test outside the checkout

Build a distribution, inspect its contents, install it into a fresh environment and run the installed command from outside the source directory. Otherwise local files may hide a missing packaged module or data resource.

tomllib is standard in Python 3.11 and later, but building and installing distributions requires a host toolchain and the chosen backend. The browser parser does not run pip or publish artifacts. Dependencies and locks should be intentional; neither replaces correct metadata.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. import tomllib

    Use the Python 3.11+ standard TOML reader.

  2. metadata = tomllib.loads(text)

    Parse fixed metadata without writing files.

  3. print(metadata["project"]["name"])

    Read the distribution's declared name.

  4. print(metadata["project"]["scripts"]["study"])

    Read the command target; this does not import it.

pyproject.toml records build/project metadata according to the chosen tooling. Declare Python compatibility, dependencies and entry points; use a clean environment to test installation. Build artefacts and dependency locks are not substitutes for source and a supported runtime policy.

Predict before you run

Does this sample install study?

Inspect metadata without installing anythingPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Rename the public command.

Try: Change the scripts key study to review and update its lookup.

The target can stay the same while the declared command name changes.

Remove the target.

Try: Delete the study entry but leave its lookup.

The dictionary read raises KeyError rather than proving a command exists.

Before you move on

The metadata target is valid text but study.cli is missing from the wheel. Will metadata parsing catch that?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

No. Inspect and install the built artifact, then invoke its command outside the source tree to exercise the missing-module boundary.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
03

Parse explicit CLI arguments

An argument parser converts a declared command grammar into structured values. Supplying explicit arguments makes a parser example repeatable.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

The original argparse program shows required numeric positionals without relying on the browser runner's own process arguments.

Words you will see

Positional argument
An argument identified by its position rather than a flag name.
nargs
A parser setting describing how many argument values to accept.
Namespace
The object argparse uses to store parsed attributes.

Read the original parser

The minutes positional uses type=int, so 10 and 15 become integers. nargs='+' means at least one value is required. parse_args receives an explicit list and returns a namespace whose minutes attribute is a list of those integers.

total then sums the numeric list and the outer print displays 25. A missing positional is a parser error, not the same contract as total([]), which returns zero. This separation lets arithmetic and command grammar be tested independently.

Know what was not validated

int accepts negative integer text. If negative study minutes are forbidden, add a domain check or a dedicated argument converter. Do not silently clamp invalid values to zero unless that is the declared behavior.

argparse normally reports invalid syntax on stderr and exits via SystemExit. Explicit lists work in the browser, but launching the installed executable, observing process status and testing packaging belong in a host lab. Keep unsupported execution errors visible.

The original example, step by step

These steps explain the original code below. They do not change when you edit your own experiment.

  1. def total(values):

    Keep summation independent of the parser.

  2. parser = argparse.ArgumentParser(description='Add study minutes')

    Create a parser with a human-readable purpose.

  3. args = parser.parse_args(['10', '15'])

    Parse known strings rather than global process arguments.

  4. print(total(args.minutes))

    Pass converted numbers to the core and display 25.

Passing an explicit argument list keeps the example deterministic and makes the parser testable without changing global sys.argv.

Predict before you run

What type are the parsed minutes?

Parse explicit CLI argumentsPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Change one thing; explain the difference.

Add one value.

Try: Use ['10', '15', '5'] as the explicit list.

The total becomes 30.

Test invalid text.

Try: Use ['ten'] as the explicit list.

The parser reports a conversion error instead of printing a fabricated total.

Before you move on

If the supplied list is empty, does this parser call total([]) and print zero?

Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

Read a worked answer

No. nargs='+' requires at least one value. argparse reports a usage error and exits before the summation call.

This is a self-check, not a required quiz or a saved score. You can revisit any concept.
DETAILED WALKTHROUGH / NOT JUST A SUMMARY

Separate the executable boundary from useful computation

The parser fixture accepts an explicit list containing 10 and 15, converts them to integers, and passes them to a summing function to print 25. This deliberately avoids process-global argument mutation. A real command needs three distinguishable responsibilities: parse user intent, perform the calculation, and format its outcome. Keeping these boundaries separate lets a business-rule test call a function without constructing a shell command or capturing terminal output.

Specify the public command contract before selecting packaging tools. Define required arguments, supported value ranges, output format, diagnostics, and exit behavior. Help output should explain units and defaults. Missing positional arguments are parser failures; negative study minutes are domain failures if the parser merely accepts integers. Preserve that distinction internally while translating expected user mistakes into concise stderr messages and a documented nonzero exit status at the outer boundary.

Make installation an explicit artifact contract

Use pyproject.toml to declare the chosen build backend, project metadata, Python compatibility, dependencies, and a console entry point when required. An entry point connects an installed command name to an importable callable. It is not equivalent to keeping a runnable script in the checkout. Decide which package files and data resources belong in the distribution and inspect the built artifact so accidental omissions or unintended sensitive files are noticed before release.

Build and test installation in a fresh environment using the documented supported interpreter. Launch the installed command from a directory outside the source tree to prevent local imports from masking an incomplete wheel. Run a small valid invocation, help, and an invalid invocation. These steps answer different questions from unit tests: the package can install, the entry point resolves, resources are present, and the executable boundary actually presents the promised observable behavior.

Design failure and output behavior for automation

A command's stdout may be consumed by another program, so keep successful structured output separate from human diagnostics on stderr. Choose whether a report includes a trailing newline and stable key order, then assert those details where they are contractual. Do not catch every exception and print zero or an empty report; that makes an internal defect indistinguishable from a genuine calculation on empty data and can corrupt downstream automation.

Handle file ownership explicitly when the command grows beyond positional numbers. Validate input and destination policy before destructive writes, close streams on exceptions, and avoid leaving a partial destination presented as complete. Cancellation or interruption should produce a failed operation, not a success message emitted before work finishes. Bound payload sizes and error context, and never place credentials in command examples or diagnostics because terminal histories and process listings can expose arguments.

Release only what the evidence supports

A practical CI sequence runs pure-function and parser tests, builds the distribution, installs it cleanly, and exercises the installed command. Test every advertised Python version or narrow the compatibility statement. Keep dependency updates intentional and inspect release contents. A dependency lock can improve repeatability for an application workflow, but it does not replace correct package metadata or prove compatibility with every supported installation scenario.

Plan version changes around users' saved configuration and output consumers, not merely around source edits. If a new output format breaks a script, provide an explicit compatibility decision. Publish through approved release credentials and preserve the ability to reinstall a known version. The lesson's in-process parser demonstration establishes none of this release machinery; it is a useful first slice whose limitations should guide the next tests rather than be concealed by a shipping checklist.

Transfer question: An installed command works only when launched from its source checkout. What should the next release attempt prove?

Inspect the distribution for missing modules and data, verify that the entry point targets an installed callable, and remove reliance on the checkout working directory or ad hoc search paths. Rebuild, install into a fresh environment, and invoke from an unrelated directory. Assert successful output, help behavior, stderr, and failure exit status. Test resource access using package-aware loading rather than relative filesystem assumptions. A green parser unit test remains useful, but it cannot substitute for this installed-artifact test because it bypasses the failing packaging and command-resolution boundary.

RECALL BEFORE YOU SCROLL

Can you explain it?

Try from memory. Feedback stays on this page and does not award judged progress.

Why separate CLI parsing from business logic?
TRANSFER THE IDEA

Rebuild: Parse explicit CLI arguments

Without copying the worked code, reproduce its observable contract: Passing an explicit argument list keeps the example deterministic and makes the parser testable without changing global sys.argv. Then change one boundary input and explain the result.

Your practice starterPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

MAKE THE RULE WORK ON NEW INPUTS

Guided practice and transfer

These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.

A short function primer before you begin

def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.

return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.

Return a value, do not only print itPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

GUIDED PRACTICE

Guided: a reusable minutes calculation

Implement the computation without reading arguments or writing output.

The contract

  • Input is a list of nonnegative exact integers representing minutes.
  • Return the integer total, including zero for empty input and every repeated value.
  • Do not print, read sys.argv or mutate the caller's list. Parsing and process exit behavior belong elsewhere.
Guided: a reusable minutes calculationPYTHON 3

Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

Preparing the editor controls. Run and editing become available when this page is interactive.

Browser Python limits

Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

Inspect 6 public checks

Transparent local learning checks, not exhaustive or tamper-proof grading.

  1. ordinary minutes
    import copy
    
    source = [10, 15]
    before = copy.deepcopy(source)
    result = total_minutes(source)
    assert type(result) is int, "Wrong result type"
    expected = 25
    observed = result
    assert observed == expected, "Wrong result value"
    def same_types(actual, target):
        if type(actual) is not type(target):
            return False
        if type(target) in (list, tuple):
            return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
        if type(target) is dict:
            return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
        return True
    assert same_types(observed, expected), "Wrong nested value type"
    assert source == before, "Caller input changed"
    
  2. empty minutes
    import copy
    
    source = []
    before = copy.deepcopy(source)
    result = total_minutes(source)
    assert type(result) is int, "Wrong result type"
    expected = 0
    observed = result
    assert observed == expected, "Wrong result value"
    def same_types(actual, target):
        if type(actual) is not type(target):
            return False
        if type(target) in (list, tuple):
            return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
        if type(target) is dict:
            return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
        return True
    assert same_types(observed, expected), "Wrong nested value type"
    assert source == before, "Caller input changed"
    
  3. repeated minutes
    import copy
    
    source = [5, 5, 5]
    before = copy.deepcopy(source)
    result = total_minutes(source)
    assert type(result) is int, "Wrong result type"
    expected = 15
    observed = result
    assert observed == expected, "Wrong result value"
    def same_types(actual, target):
        if type(actual) is not type(target):
            return False
        if type(target) in (list, tuple):
            return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
        if type(target) is dict:
            return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
        return True
    assert same_types(observed, expected), "Wrong nested value type"
    assert source == before, "Caller input changed"
    
  4. zero boundary
    import copy
    
    source = [0]
    before = copy.deepcopy(source)
    result = total_minutes(source)
    assert type(result) is int, "Wrong result type"
    expected = 0
    observed = result
    assert observed == expected, "Wrong result value"
    def same_types(actual, target):
        if type(actual) is not type(target):
            return False
        if type(target) in (list, tuple):
            return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
        if type(target) is dict:
            return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
        return True
    assert same_types(observed, expected), "Wrong nested value type"
    assert source == before, "Caller input changed"
    
  5. one minute
    import copy
    
    source = [1]
    before = copy.deepcopy(source)
    result = total_minutes(source)
    assert type(result) is int, "Wrong result type"
    expected = 1
    observed = result
    assert observed == expected, "Wrong result value"
    def same_types(actual, target):
        if type(actual) is not type(target):
            return False
        if type(target) in (list, tuple):
            return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
        if type(target) is dict:
            return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
        return True
    assert same_types(observed, expected), "Wrong nested value type"
    assert source == before, "Caller input changed"
    
  6. preserve order
    import copy
    
    source = [9, 2, 7]
    before = copy.deepcopy(source)
    result = total_minutes(source)
    assert type(result) is int, "Wrong result type"
    expected = 18
    observed = result
    assert observed == expected, "Wrong result value"
    def same_types(actual, target):
        if type(actual) is not type(target):
            return False
        if type(target) in (list, tuple):
            return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
        if type(target) is dict:
            return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
        return True
    assert same_types(observed, expected), "Wrong nested value type"
    assert source == before, "Caller input changed"
    
    What is still untested by this calculation?

    Parsing, output channels, installation and exit status. Summation uses O(n) additions and O(1) accumulator slots; very large integer arithmetic has additional digit costs.

    GUIDED PRACTICE

    Guided: inspect a declared command

    Look up a script target in parsed project metadata without importing or installing anything.

    The contract

    • Input is a dictionary with project.scripts mapping command strings to target strings; an optional command argument defaults to study.
    • Return its exact target or the empty string for a missing command. Preserve case and punctuation.
    • Do not mutate metadata, import the target, run a shell or claim installation. The schema itself is trusted in this exercise.
    Guided: inspect a declared commandPYTHON 3

    Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

    Preparing the editor controls. Run and editing become available when this page is interactive.

    Browser Python limits

    Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

    Inspect 6 public checks

    Transparent local learning checks, not exhaustive or tamper-proof grading.

    1. study target
      import copy
      
      source = {"project": {"scripts": {"study": "study.cli:main"}}}
      before = copy.deepcopy(source)
      result = script_target(source)
      assert type(result) is str, "Wrong result type"
      expected = "study.cli:main"
      observed = result
      assert observed == expected, "Wrong result value"
      def same_types(actual, target):
          if type(actual) is not type(target):
              return False
          if type(target) in (list, tuple):
              return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
          if type(target) is dict:
              return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
          return True
      assert same_types(observed, expected), "Wrong nested value type"
      assert source == before, "Caller input changed"
      
    2. empty script map
      import copy
      
      source = {"project": {"scripts": {}}}
      before = copy.deepcopy(source)
      result = script_target(source)
      assert type(result) is str, "Wrong result type"
      expected = ""
      observed = result
      assert observed == expected, "Wrong result value"
      def same_types(actual, target):
          if type(actual) is not type(target):
              return False
          if type(target) in (list, tuple):
              return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
          if type(target) is dict:
              return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
          return True
      assert same_types(observed, expected), "Wrong nested value type"
      assert source == before, "Caller input changed"
      
    3. same target for two commands
      import copy
      
      source = {"project": {"scripts": {"study": "tool:main", "review": "tool:main"}}}
      before = copy.deepcopy(source)
      result = script_target(source, "review")
      assert type(result) is str, "Wrong result type"
      expected = "tool:main"
      observed = result
      assert observed == expected, "Wrong result value"
      def same_types(actual, target):
          if type(actual) is not type(target):
              return False
          if type(target) in (list, tuple):
              return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
          if type(target) is dict:
              return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
          return True
      assert same_types(observed, expected), "Wrong nested value type"
      assert source == before, "Caller input changed"
      
    4. missing command
      import copy
      
      source = {"project": {"scripts": {"other": "tool:main"}}}
      before = copy.deepcopy(source)
      result = script_target(source)
      assert type(result) is str, "Wrong result type"
      expected = ""
      observed = result
      assert observed == expected, "Wrong result value"
      def same_types(actual, target):
          if type(actual) is not type(target):
              return False
          if type(target) in (list, tuple):
              return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
          if type(target) is dict:
              return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
          return True
      assert same_types(observed, expected), "Wrong nested value type"
      assert source == before, "Caller input changed"
      
    5. case-sensitive command
      import copy
      
      source = {"project": {"scripts": {"Study": "caps:run", "study": "lower:run"}}}
      before = copy.deepcopy(source)
      result = script_target(source, "Study")
      assert type(result) is str, "Wrong result type"
      expected = "caps:run"
      observed = result
      assert observed == expected, "Wrong result value"
      def same_types(actual, target):
          if type(actual) is not type(target):
              return False
          if type(target) in (list, tuple):
              return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
          if type(target) is dict:
              return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
          return True
      assert same_types(observed, expected), "Wrong nested value type"
      assert source == before, "Caller input changed"
      
    6. target text stays exact
      import copy
      
      source = {"project": {"scripts": {"study": "package.submodule:entry"}}}
      before = copy.deepcopy(source)
      result = script_target(source)
      assert type(result) is str, "Wrong result type"
      expected = "package.submodule:entry"
      observed = result
      assert observed == expected, "Wrong result value"
      def same_types(actual, target):
          if type(actual) is not type(target):
              return False
          if type(target) in (list, tuple):
              return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
          if type(target) is dict:
              return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
          return True
      assert same_types(observed, expected), "Wrong nested value type"
      assert source == before, "Caller input changed"
      
      Does a nonempty target prove that importing it succeeds?

      No. This is metadata inspection only. Ordinary mapping lookup is average O(1) per fixed level, apart from key hashing; actual distribution installation needs a host smoke test.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: add a command boundary

      The core now receives argument strings and must model success or validation failure with separate channels.

      The contract

      • Input is a finite list of strings. Accept int-compatible nonnegative values; reject malformed or negative values.
      • Return exactly (0, '<total>\n', '') on success or (2, '', 'invalid minutes\n') on expected input failure. Empty input is a valid zero total.
      • Do not print, mutate sys.argv, launch a process or mutate input. This tuple models an adapter and is not an operating-system exit.
      Transfer: add a command boundaryPYTHON 3

      Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

      Preparing the editor controls. Run and editing become available when this page is interactive.

      Browser Python limits

      Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

      Inspect 6 public checks

      Transparent local learning checks, not exhaustive or tamper-proof grading.

      1. successful channels
        import copy
        
        source = ["10", "15"]
        before = copy.deepcopy(source)
        result = command_outcome(source)
        assert type(result) is tuple, "Wrong result type"
        expected = (0, "25\n", "")
        observed = result
        assert observed == expected, "Wrong result value"
        def same_types(actual, target):
            if type(actual) is not type(target):
                return False
            if type(target) in (list, tuple):
                return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
            if type(target) is dict:
                return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
            return True
        assert same_types(observed, expected), "Wrong nested value type"
        assert source == before, "Caller input changed"
        assert type(result[0]) is int and all(type(value) is str for value in result[1:])
      2. empty argument list
        import copy
        
        source = []
        before = copy.deepcopy(source)
        result = command_outcome(source)
        assert type(result) is tuple, "Wrong result type"
        expected = (0, "0\n", "")
        observed = result
        assert observed == expected, "Wrong result value"
        def same_types(actual, target):
            if type(actual) is not type(target):
                return False
            if type(target) in (list, tuple):
                return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
            if type(target) is dict:
                return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
            return True
        assert same_types(observed, expected), "Wrong nested value type"
        assert source == before, "Caller input changed"
        
      3. repeated values
        import copy
        
        source = ["5", "5"]
        before = copy.deepcopy(source)
        result = command_outcome(source)
        assert type(result) is tuple, "Wrong result type"
        expected = (0, "10\n", "")
        observed = result
        assert observed == expected, "Wrong result value"
        def same_types(actual, target):
            if type(actual) is not type(target):
                return False
            if type(target) in (list, tuple):
                return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
            if type(target) is dict:
                return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
            return True
        assert same_types(observed, expected), "Wrong nested value type"
        assert source == before, "Caller input changed"
        
      4. malformed value
        import copy
        
        source = ["later"]
        before = copy.deepcopy(source)
        result = command_outcome(source)
        assert type(result) is tuple, "Wrong result type"
        expected = (2, "", "invalid minutes\n")
        observed = result
        assert observed == expected, "Wrong result value"
        def same_types(actual, target):
            if type(actual) is not type(target):
                return False
            if type(target) in (list, tuple):
                return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
            if type(target) is dict:
                return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
            return True
        assert same_types(observed, expected), "Wrong nested value type"
        assert source == before, "Caller input changed"
        
      5. negative domain value
        import copy
        
        source = ["-1", "5"]
        before = copy.deepcopy(source)
        result = command_outcome(source)
        assert type(result) is tuple, "Wrong result type"
        expected = (2, "", "invalid minutes\n")
        observed = result
        assert observed == expected, "Wrong result value"
        def same_types(actual, target):
            if type(actual) is not type(target):
                return False
            if type(target) in (list, tuple):
                return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
            if type(target) is dict:
                return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
            return True
        assert same_types(observed, expected), "Wrong nested value type"
        assert source == before, "Caller input changed"
        
      6. zero with whitespace
        import copy
        
        source = [" 0 ", "+2"]
        before = copy.deepcopy(source)
        result = command_outcome(source)
        assert type(result) is tuple, "Wrong result type"
        expected = (0, "2\n", "")
        observed = result
        assert observed == expected, "Wrong result value"
        def same_types(actual, target):
            if type(actual) is not type(target):
                return False
            if type(target) in (list, tuple):
                return len(actual) == len(target) and all(same_types(a, b) for a, b in zip(actual, target))
            if type(target) is dict:
                return actual.keys() == target.keys() and all(same_types(actual[key], target[key]) for key in target)
            return True
        assert same_types(observed, expected), "Wrong nested value type"
        assert source == before, "Caller input changed"
        assert type(result[0]) is int and type(result[1]) is str and type(result[2]) is str
        What changed from the pure total function?

        The boundary parses text and classifies expected errors while keeping success and diagnostic channels separate. For n arguments it uses O(n) numeric storage and work plus text conversion costs; installed-process behavior still needs host verification.

        A GOOD PLACE TO PAUSE

        Core route complete.

        If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.

        Save your core reading milestone

        CI should prove installability

        A command's successful data and its diagnostics are different output channels. Exit status tells automation whether the operation completed successfully.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        A pipeline consuming JSON or a numeric total can be broken by an error message mixed into stdout, even if a human reader understands it.

        Words you will see

        stdout
        The standard output stream for a command's result.
        stderr
        A separate stream for diagnostics.
        Exit status
        A process result code, conventionally zero for success and nonzero for failure.

        Specify three observable results

        The fixture models the command outcome as status, stdout text and stderr text. Valid numeric arguments return status zero with a trailing newline in stdout. Invalid text returns status two, empty stdout and a concise diagnostic.

        Returning this tuple is an in-process model, not an actual process exit. A host main can write the two strings to their respective streams and return the status to its launcher. Test both the pure model and that real outer adapter.

        Do not hide internal failures

        The example catches only the expected integer conversion error. Catching every exception and returning a success-shaped zero would conceal programming defects. Keep error context bounded and avoid echoing secrets or entire payloads into terminal logs.

        Choose output formatting deliberately if scripts consume it. A newline, JSON key spelling or diagnostic stream can be a compatibility promise. Browser execution cannot demonstrate an installed command's operating-system exit code; report that remaining host requirement honestly.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. def command(argv):

          Receive explicit arguments without launching a process.

        2. except ValueError:

          Translate the declared invalid-text case only.

        3. return 0, f"{total}\n", ""

          Keep successful data separate from diagnostics.

        4. print(command(["later"]))

          Inspect the failure tuple as model data, not a process status.

        Build the distribution, install it in a fresh environment and run unit/integration checks plus a CLI smoke test. Avoid relying on imports that work only from the repository root. Verify package data, entry points and supported Python versions.

        Predict before you run

        Where does the invalid-text diagnostic belong?

        Model command status and channelsPYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Observe an empty sum.

        Try: Inspect command([]).

        The model returns zero and '0\n'; a separate parser can choose to forbid no arguments.

        Change the output contract.

        Try: Return a JSON object string for successful results.

        Consumers and tests must adapt deliberately; changing format is not merely cosmetic.

        Before you move on

        A command returns a nonzero status but prints a partial success report to stdout. Is the channel contract automatically safe?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        No. Downstream consumers may use that data. Define partial-output behavior and prefer empty stdout for expected validation failures before work starts.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Dependencies and release safety

        A release check should prove the installed artifact's public contract, not just imports from the developer's checkout. Versioned behavior includes data formats and command names.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Unit tests can stay green while a wheel omits a resource. A bounded manifest inspection is a first check, followed by real clean-environment installation.

        Words you will see

        Artifact
        A built deliverable such as a wheel.
        Smoke test
        A short check that a public entry path works at all.
        Compatibility
        Preserving the supported expectations of existing users and tools.

        Inspect what will ship

        The fixed manifest contains a module, resource and metadata file. Subtracting it from the required set reports the missing CLI module. Sorting makes the diagnostic stable; it does not change set semantics.

        A manifest comparison can identify absent files but cannot prove they are valid or importable. Build, install in a fresh environment, invoke outside the checkout, and check help, valid input and invalid input on each supported Python version.

        Release safely and reversibly

        Keep secrets out of source, wheels and diagnostics. Inspect dependencies intentionally and publish immutable versioned artifacts through approved release accounts. This fixture uses no credentials, uploads or real package index.

        Changing a command name or output format can break user automation even if arithmetic stays correct. Plan migrations and rollback around saved configuration and consumers. Browser Python can inspect manifest data but cannot establish a real installation or publish guarantee.

        The original example, step by step

        These steps explain the original code below. They do not change when you edit your own experiment.

        1. manifest = {"study/__init__.py", "study/data.json", "study_tool.dist-info/METADATA"}

          Supply a fictional artifact's file names.

        2. required = {"study/__init__.py", "study/cli.py", "study/data.json"}

          State the files this command needs.

        3. missing = sorted(required - manifest)

          Find absent required files and stabilize the display.

        4. print(not missing)

          Report False because the CLI file is absent.

        Review dependencies, keep secrets out of source/wheels and publish immutable versioned artefacts through an approved account. Do not instruct users to run arbitrary remote shell installation scripts. Define rollback and compatibility for saved data or configuration.

        Predict before you run

        Which requirement is absent?

        Detect an omitted command modulePYTHON 3

        Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.

        Preparing the editor controls. Run and editing become available when this page is interactive.

        Browser Python limits

        Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.

        Change one thing; explain the difference.

        Include the missing file.

        Try: Add "study/cli.py" to manifest.

        missing becomes [] and the Boolean becomes True, but installation is still unproven.

        Require a second resource.

        Try: Add "study/help.txt" to required.

        The missing report includes the help resource in sorted order.

        Before you move on

        Every required filename exists, but the entry point names the wrong callable. What check still matters?

        Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.

        Read a worked answer

        Install and invoke the command outside the checkout. Presence alone does not prove import resolution, callable existence or successful execution.

        This is a self-check, not a required quiz or a saved score. You can revisit any concept.

        Make the explanation your own.

        Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.

        Take a versioned study copy

        Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.

        Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.

        REFLECT, THEN CONTINUE

        Make this a milestone.

        Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.

        Your account

        Loading account...

        Sign in to save your work across devices.