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 49 / BUILDING AND SHIPPING

Modules and reproducible environments

Organise a program and isolate its dependencies.

FoundationTutorial 10 min core+8 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 building Python foundations; revisit the preparation topics whenever the vocabulary is unfamiliar.

Explore the connected curriculum and preparation map

Lesson content version 2026-10-27. Suggested core budget: 10 minutes; optional deep dive: 8 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.

Virtual environments and installation commands need your own local toolchain; browser snippets cannot install packages.

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
  • Import standard-library modules
  • Explain the main guard
  • Use virtual environments deliberately
01

Import a responsibility

A module is a named unit of Python code. Importing lets you use its definitions through a namespace instead of copying their implementation into your program.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Use a reviewed standard-library tool when its contract matches the problem. A frequency table is a good example: Counter already defines counting and missing-count behavior. Start with lists and dictionaries; importing chooses where those reusable definitions come from.

Words you will see

Module
A loadable unit of Python definitions with a name.
Namespace
A collection of name-to-object bindings.
Package
A module that can contain submodules; it organises import names, not necessarily one installable distribution.

Import a tool with a matching contract

from collections import Counter binds the Counter class directly in this program's namespace. Counter reads each input occurrence and keeps a count per value: read occurs twice, code once. Reading an absent count gives zero instead of the KeyError an ordinary dictionary subscription would raise.

import collections is an alternative that keeps the module prefix visible: collections.Counter(...). An alias can shorten a long name without changing the imported object's behavior. Avoid import * because it makes name ownership and collisions harder to see.

Names are part of the dependency boundary

A local file named collections.py can shadow the standard library in a real project, causing confusing imports. Choose application-specific module names and separate responsibilities. A package such as reports.parsers can organise related modules; it is not the same concept as a versioned package distribution installed by pip.

This example uses only a standard-library module supplied by browser Python. It does not install anything, search the network or create files. A third-party dependency is usable only if the approved runtime provides it; an import failure should remain visible rather than trigger an unapproved download.

The original example, step by step

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

  1. from collections import Counter

    Bind the standard-library counting tool.

  2. counts = Counter(["read", "code", "read"])

    Count all three occurrences while retaining the repeated read.

  3. print(counts["read"])

    Print 2 for the observed word.

  4. print(counts["missing"])

    Print 0 using Counter's documented missing-count behavior.

A module is a unit of Python code with a namespace. Import standard-library tools instead of reimplementing common utilities. Avoid filenames such as json.py or math.py that shadow the library you meant to use.

Conceptual name ownership, not a measured import trace

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

  1. Library namespacecollections provides the Counter definition.
  2. Local bindingfrom collections import Counter binds that tool as Counter here.
  3. Owned instanceCounter([...]) creates this program's counts, separate from the module definition.
Predict before you run

Why does counts['missing'] print 0?

A focused library callPYTHON 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.

Use an explicit namespace.

Try: Replace the import with import collections and Counter( with collections.Counter(.

The output remains 2 then 0, but the tool's module is visible at its call site.

Count another occurrence.

Try: Append "code" to the input list and print counts["code"].

The added print displays 2; the existing read and missing outputs remain unchanged.

Before you move on

If you switch to import collections, can the next line still use an unqualified Counter name?

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

Not unless you also bind Counter separately. Use collections.Counter. The module import and the from-import introduce different local names.

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

Separate import from execution

The main guard separates reusable definitions from work intended only for direct script execution. __name__ tells a module the name under which it is executing.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

A utility should be safe to import for its functions without also printing a report or starting a job. Put definitions at module level and direct-run orchestration under a guard. This browser example needs no separate host module files.

Words you will see

__name__
The execution name of a module; direct script execution normally uses '__main__'.
Main guard
The if __name__ == '__main__' condition selecting direct-run work.
Module-level statement
A statement executed while loading a module rather than waiting inside a function.

Definitions load in both modes

The authored source defines answer before reaching its guard. Under report_tools the condition is false, so it prints nothing during that execution. The caller can still retrieve answer and print its result. Under __main__ the condition is true, so the source itself prints 42.

The guard does not hide definitions, create a separate scope, or prevent all side effects. Any statements outside it still execute. Put reusable definitions outside; put launching logic inside. For a real package entry point, keep that launching function small and test the underlying logic directly.

Understand what the browser model can establish

exec here receives only a fixed, visible, authored source string and explicit names. It is not a data parser, not a security sandbox and not a substitute for importing untrusted code. Never adapt this pattern to execute uploaded JSON or arbitrary user data.

A real import also has discovery, module objects and caching behavior that this controlled namespace model does not reproduce. Those concerns belong in the next sections and a supported local project lab. No generated module files, shell commands or child processes are required for this program.

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_scope = {"__name__": "report_tools"}

    Select a non-main execution name for the model.

  2. exec(source, import_scope)

    Define answer; the guard suppresses source-level printing.

  3. print(import_scope["answer"]())

    The caller prints 42 using the reusable definition.

  4. print("script mode")

    Label the next modeled execution.

  5. exec(source, {"__name__": "__main__"})

    Execute the fixed source with a true guard, printing 42 from inside it.

if __name__ == '__main__': controls work that should run when a file is launched as a script, rather than when it is imported. Put reusable functions outside that block.

Predict before you run

How many 42 lines appear in the original output?

Model script and import modesPYTHON 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.

Remove the direct-run call.

Try: Remove the final exec(source, {"__name__": "__main__"}) line.

The first 42 and script mode remain, but the last 42 disappears.

Change the reusable calculation.

Try: Change return 42 inside source to return 7.

Both numeric lines become 7 because both executions use the same definition text.

Before you move on

Where should a reusable format_report function live if both imports and script runs need it?

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

Outside the guard. Put only its direct-run invocation under the guard, so importers can access the definition without triggering the script's work.

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

Isolate dependencies per project

A project environment selects an interpreter and installed dependencies for a project. Reproducibility means recording those choices rather than relying on an unknown global setup.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Code that works on one machine may fail under another Python version or missing dependency. Record the version and dependency choices that matter. Keep the distinction between declaring an environment and actually creating or verifying one.

Words you will see

Interpreter
The Python program that executes your source.
Virtual environment
A project-specific Python environment with its own installed-package location.
Dependency
Another library or component your program needs to run.

A declaration is not a measurement

The dictionary explicitly declares Python 3.12, browser operation and no third-party dependencies. Printing those fields shows what this hypothetical project requests, not what sys.version reports. An empty dependency tuple means none are listed; it does not prove a running system has none installed.

This lesson's examples need only the standard library. The controlled validation uses pinned Python separately. A deployed browser interpreter can have a different version and available module set; report incompatibilities visibly rather than printing the declared version as if it were detected.

Use environment tools only where they are supported

In an ordinary local terminal, python -m venv .venv creates an environment. python -m pip ties installation to the selected interpreter; activation is shell-specific convenience, not a change to the Python language. These commands are local lab instructions, not runnable browser Python.

A project should record supported Python versions, direct dependencies and a reviewed resolution strategy, including transitive versions where needed. A venv is dependency isolation, not protection from malicious package code or host access. The browser runner cannot create your host venv, install arbitrary packages or promise persistent project files.

The original example, step by step

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

  1. requirements = {"python": "3.12", "runtime": "browser", "dependencies": ()}

    Declare a small project contract as ordinary data.

  2. print(requirements["python"])

    Print its requested version, not runtime detection.

  3. print(requirements["runtime"])

    Print its declared environment.

  4. print(len(requirements["dependencies"]))

    Show that this declaration lists zero third-party dependencies.

python -m venv .venv creates an environment. Activation differs by shell; python -m pip makes the chosen interpreter explicit. Record dependencies and supported versions rather than relying on whatever is globally installed.

Predict before you run

What does the final zero establish?

Describe an environment contractPYTHON 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.

Declare one hypothetical dependency.

Try: Change () to ("example-lib==1.0",).

The final count becomes 1; nothing is installed and no import is attempted.

Change a declared target only.

Try: Replace "browser" with "local lab".

The label changes, but execution remains in the same runner.

Before you move on

If the declaration says 3.12 while a runner actually uses 3.13, which version executes the code?

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

3.13. Data cannot select or replace the interpreter that is already running. A real setup must choose the executable and verify it independently.

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

Build import boundaries around responsibilities

A module provides a namespace and a place to group related behavior. In the Counter example, the counting responsibility belongs to collections rather than to a new hand-written utility: read occurs twice and an absent key has count zero. Importing that focused tool communicates intent. Separate domain calculation, input decoding, and command execution so importing a calculation does not accidentally parse arguments or contact a remote service.

Imports execute top-level statements when the module is first loaded in a process, then normally reuse its cached module object. Put launch behavior behind the main guard and expose reusable functions outside it. Test an import while capturing output and substituting external boundaries if necessary. A quiet import is especially valuable for test discovery and command tooling, where importing one helper should not start a report or create application state.

Diagnose import failures from the selected interpreter

When an import fails, establish which interpreter launched the program, where its packages are installed, and which module path Python actually resolved. A local file named json.py or math.py can shadow the standard library. The resulting error may look like a broken library even though resolution selected the wrong source. Rename the conflicting module deliberately and rerun from the intended launch location rather than adding arbitrary search paths.

Circular imports often expose a responsibility cycle. If module A needs a value from B while B is still importing A, a partially initialized namespace can cause confusing failures. Move a shared domain contract to a lower-level module or invert the dependency through an injected function. A local import can sometimes defer an unavoidable dependency, but scattering deferred imports merely hides an architectural cycle and can shift failures into rarely tested execution paths.

Treat an environment as a reproducible dependency choice

Create a project virtual environment with the interpreter version you intend to support. Activation changes shell command resolution; invoking that environment's interpreter directly is another way to make selection explicit. Use the chosen interpreter with -m pip so installation and execution target the same environment. Record direct dependencies, supported Python versions, and the installation procedure rather than relying on packages that happen to exist globally on one workstation.

Dependency metadata and a resolved lock serve different purposes. Metadata expresses compatibility requirements; a lock can record a chosen resolution for a particular workflow. Review updates and recreate the environment from recorded inputs when testing reproducibility. A virtual environment is not a security sandbox: installed code still runs with the process's permissions and can access resources available to that user. Isolation of package names is not isolation of files, credentials, or network authority.

Verify reuse separately from the tiny library fixture

The lesson challenge sorts 4, 9, 1, 7, and 3 descending and keeps the first three values, producing 9, 7, and 4. That verifies a standard-library operation on an explicit sequence. It does not create multiple modules, install a package, or prove that another developer can import the project. Build those demonstrations independently, including imports from outside the repository root where accidental local resolution cannot mask missing packaging metadata.

A useful environment acceptance sequence recreates dependencies, imports the library without side effects, runs tests, and launches the documented command. Include a missing-dependency failure with a clear remediation rather than silently installing during normal execution. Keep optional integrations optional at their own boundaries. If an upgrade fails, preserve the previous supported resolution and the failing evidence; avoid editing unrelated source simply to accommodate an environment that was selected by mistake.

Transfer question: Tests pass in an editor, but the same project fails to import in a shell. What is your investigation order?

Compare the exact interpreter paths and versions first, then inspect the shell working directory and resolved module locations. Check whether the editor selected a virtual environment that the shell did not. Run installation through the intended interpreter and look for local filenames shadowing dependencies. Next test from outside the repository to expose imports that rely on its root being on the search path. Do not start by globally installing every missing package or appending arbitrary directories. Once the cause is known, document a repeatable launch and installation procedure and verify it in a fresh project environment.

RECALL BEFORE YOU SCROLL

Can you explain it?

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

Does a virtual environment sandbox malicious code?
TRANSFER THE IDEA

Use the standard library

Print the three largest values in descending order using sorted.

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: use Counter without sharing state

Use a stdlib responsibility and return a plain, independently owned result.

The contract

  • Input is a list of case-sensitive strings. Count exact occurrences, including empty strings and repeated words.
  • Return a fresh plain dict in first-occurrence key order. Empty input returns a fresh {}. Do not alter input.
  • Use collections.Counter; no packages, files, network, global cache or installation. Repeated calls must not accumulate earlier counts.
Guided: use Counter without sharing statePYTHON 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. counts
    result = word_counts(["read","code","read"])
    assert type(result) is dict and result == {"read":2,"code":1}
  2. empty
    a = word_counts([])
    b = word_counts([])
    assert a == {} and b == {} and a is not b
  3. case
    assert word_counts(["A","a"]) == {"A":1,"a":1}
  4. empty word and repeats
    assert word_counts(["","x",""]) == {"":2,"x":1}
  5. order
    assert list(word_counts(["z","a","z"])) == ["z","a"]
  6. caller and state
    words = ["b","a","b"]
    a = word_counts(words)
    a["b"] = 99
    assert words == ["b","a","b"] and word_counts(words) == {"b":2,"a":1} and word_counts(["a"]) == {"a":1}
    Does this check prove that Counter, rather than a handwritten loop, was used?

    No. Public behavior checks establish this result contract, not implementation provenance. Under ordinary hashing, n words and u distinct values need average O(n) counting time and O(u) result storage, apart from string hashing costs.

    GUIDED PRACTICE

    Guided: separate a reusable result

    Design a pure summary function that a real main guard could call without putting display work into the helper.

    The contract

    • Input is a list of strings. Return (total_items, distinct_items) as a tuple of integers. Empty strings count as values; repeats increase total but not distinct.
    • The helper must not print, mutate input, read files or retain state. Empty input returns (0, 0). No sorting or installation.
    • This exercise tests the reusable helper only. It does not create files or simulate a real import; a local application may call the helper from its main guard.
    Guided: separate a reusable resultPYTHON 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
      assert summary_counts(["a","b","a"]) == (3,2)
    2. empty
      assert summary_counts([]) == (0,0)
    3. repeats
      assert summary_counts(["a","a","a"]) == (3,1)
    4. empty string
      assert summary_counts(["",""]) == (2,1)
    5. no display
      import contextlib, io
      output = io.StringIO()
      with contextlib.redirect_stdout(output):
          result = summary_counts(["x"])
      assert result == (1,1) and output.getvalue() == ""
    6. ownership and isolation
      items = ["z","a","z"]
      assert summary_counts(items) == (3,2) and items == ["z","a","z"] and summary_counts(["a"]) == (1,1)
      Why not put this function definition inside the main guard?

      Importers would then lack the definition. Keep the helper at module level and direct-run display under the guard. For n strings and u distinct values, expected O(n) set work and O(u) temporary storage assume ordinary hashing.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: reject incompatible declarations

      Change from printing one plan to merging two reviewed plans with explicit conflict handling.

      The contract

      • Inputs are dicts of package-name strings to exact version strings. Versions are opaque strings; do not infer which is newer.
      • Return a fresh dict: left entries first, then right-only entries in right order. A shared key is allowed only when both version strings are equal; otherwise raise ValueError.
      • Preserve both inputs, including on conflict. Empty inputs give a fresh empty dict. No dependency resolution, installation, network or retained mutable state.
      Transfer: reject incompatible declarationsPYTHON 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. disjoint
        assert merge_plans({"a":"1"},{"b":"2"}) == {"a":"1","b":"2"}
      2. same pin
        assert merge_plans({"a":"1"},{"a":"1"}) == {"a":"1"}
      3. conflict
        try:
            merge_plans({"a":"2"},{"a":"10"})
        except ValueError:
            pass
        else:
            raise AssertionError("Conflict was overwritten")
      4. empty ownership
        a = merge_plans({}, {})
        b = merge_plans({}, {})
        assert a == {} and b == {} and a is not b
      5. order
        assert list(merge_plans({"z":"1","a":"2"},{"b":"3","z":"1"})) == ["z","a","b"]
      6. ownership after success and conflict
        left = {"a":"1"}
        right = {"b":"2"}
        result = merge_plans(left, right)
        assert result == {"a":"1","b":"2"} and result is not left and result is not right
        try:
            merge_plans(left, {"x":"3","a":"2"})
        except ValueError:
            pass
        else:
            raise AssertionError("Conflict accepted")
        assert left == {"a":"1"} and right == {"b":"2"}
        Does agreeing on direct pins establish a reproducible installation?

        No. This is only an in-memory declaration merge; transitive resolution, artifacts and interpreter compatibility remain separate. For l and r keys, expected O(l + r) work and O(l + r) result space assume ordinary dictionary hashing.

        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

        Imports execute module code

        An ordinary import loads and executes module-level code when needed, then normally reuses a cached module object on later imports with the same name.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Putting report generation at module level can cause work merely because another module needs one helper. Understand loading and reuse so architecture does not depend on hidden import side effects or an assumed fresh module every time.

        Words you will see

        Import cache
        The sys.modules mapping normally used to reuse modules by name.
        Side effect
        An observable action beyond providing a returned value, such as output or changing global state.
        Circular import
        A dependency cycle in which modules need one another during loading.

        Reuse definitions without replaying initialization

        import_module performs an ordinary import by a string name. Both calls request fractions and, without cache manipulation or reload, return the same module object. It may already have been imported by the runner. The identity check establishes reuse here, not that this sample observed the very first load.

        Fraction is accessed through both names. The calculation remains exact: one half plus one third is five sixths. Nothing about module caching means ordinary functions stop running; each explicit Fraction construction and arithmetic call still happens when requested.

        Loading order can expose incomplete state

        During an initial load, another import in a cycle can encounter a partially initialised module whose later definitions are not bound yet. Break the responsibility cycle by moving shared definitions lower, passing a dependency explicitly or using a justified narrow deferred import.

        Avoid network requests, secret output and starting workers at import time. A main guard helps with script-only work but does not undo other top-level side effects. This fixture imports only installed stdlib; it does not create modules, change sys.path or sys.modules, reload libraries or use host files.

        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 importlib

          Get the standard-library programmatic import interface.

        2. first = importlib.import_module("fractions")

          Request the module, loading it if necessary.

        3. second = importlib.import_module("fractions")

          Request the same name again under ordinary cache behavior.

        4. print(first is second)

          Show that both references identify the same module object.

        5. print(first.Fraction(1, 2) + second.Fraction(1, 3))

          Use definitions through either reference and print exact 5/6.

        On first import, top-level statements run and the module is cached. Avoid network calls, expensive work or secret output as a side effect of import. Circular imports often signal unclear module boundaries.

        Predict before you run

        What does first is second print in this unmodified import sequence?

        Observe a cached standard-library 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.

        Inspect the shared namespace.

        Try: Add print(first.__name__, second.__name__).

        Both names print fractions; local aliases do not rename the module.

        Change calculation, not initialization.

        Try: Replace Fraction(1, 3) with Fraction(1, 2).

        Identity remains True and the sum becomes 1, showing normal calls still execute.

        Before you move on

        If a module exposes a mutable list, does importing it under a second local name copy that list?

        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. Ordinary same-name imports reuse the module; both references can see the same module state. Return fresh values or manage shared state deliberately.

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

        Supply-chain responsibility

        Dependency review checks which code and versions a project will trust. A pinned version improves repeatability but is not a guarantee of safety.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Adding a package means trusting its code and often other code it depends on. A project should deliberately review that choice, record the result and plan updates. A reproducible unsafe dependency is still unsafe.

        Words you will see

        Pin
        An exact version choice rather than an open-ended range.
        Transitive dependency
        A dependency required by another dependency.
        Supply chain
        The sources, distributions and steps that deliver executable dependencies into a project.

        Make chosen versions inspectable

        The fictional plan pairs each package name with an exact version string. sorted(plan.items()) makes the display order stable, and the f-string renders familiar name==version notation. These lines are declarations only. They neither resolve transitive dependencies nor verify a downloaded artifact.

        A real reproducibility strategy also records interpreter compatibility, platform differences and an appropriate lock or constraints policy. Hash verification can check artifact identity; it cannot prove the artifact is benign. Review sources, maintainers, licensing and advisories as part of the actual project's workflow.

        Isolation and updates need separate decisions

        A venv separates package locations so projects can choose different versions. Installed code still runs with the process's permissions. It can access resources the process can access; a venv is not a sandbox. Keep approved runtime restrictions rather than widening them just to import a package.

        Pinning indefinitely also freezes known bugs. Update intentionally with release review and relevant tests. Prefer an adequate stdlib tool when it meets the requirement, rather than adding a library for convenience alone. This browser model has no network, package manager or subprocess, and makes no live advisory or installation claims.

        The original example, step by step

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

        1. plan = {"report-tools": "1.2.0", "table-tools": "2.0.1"}

          Declare fictional exact version choices as data.

        2. for name, version in sorted(plan.items()):

          Visit dependency pairs in deterministic name order.

        3. print(f"{name}=={version}")

          Format reviewable declarations, not executed installation commands.

        4. print("declaration only; not installed")

          Make the runtime boundary explicit in the output.

        Pin and review dependencies appropriate to your deployment and update them intentionally. A virtual environment isolates packages, not malicious code or host resources; it is not a sandbox.

        Predict before you run

        Does this program make either fictional library available to import?

        Report a declared dependency planPYTHON 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.

        Change declaration order.

        Try: Reverse the two entries in plan.

        The printed package order stays alphabetical because the loop sorts pairs.

        Model an intentional update.

        Try: Change "1.2.0" to "1.2.1".

        Only the declared version changes; no update has actually been installed or validated.

        Before you move on

        Would a reviewed exact pin remove the need to test an update to a transitive dependency?

        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. A transitive change can alter behavior too. Record the resolved choice, review its impact and run the project's relevant tests; pinning alone proves neither compatibility nor safety.

        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.