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 34 / ADVANCED LANGUAGE FEATURES

Imports, module lifecycle and dependency cycles

Treat imports as executable architecture, not just file lookup.

AdvancedTutorial 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 ready to reason about Python internals, resource boundaries and the listed prerequisites.

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.

Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.

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 import executes a module once per normal cache entry
  • Apply break a cycle at the responsibility boundary
  • Reason about package structure and trust
01

Import executes a module once per normal cache entry

Import normally runs a module's top-level code once while loading it, then reuses the module stored in the interpreter's cache.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Treat import as an executable dependency boundary. Reusable modules should define tools without unexpectedly opening resources or starting work.

Words you will see

Module
An object holding a namespace of definitions and other module state.
Namespace
A mapping from names to objects.
sys.modules
The interpreter's cache mapping module names to module objects.

Definitions also execute during loading

A def statement creates a function object when the module loads, but does not run its body. A print outside a function would run immediately. A later normal import usually returns the cached module rather than repeating every top-level action.

The example imports the standard-library math module twice. The two local names refer to the same module object. sqrt is looked up on that module and called only in the final print.

Cache reuse is not a deployment mechanism

Normal cache behavior has exceptions, such as deliberate reloads or separate interpreters. Do not build correctness around repeated imports rerunning setup, and do not clear sys.modules to simulate production updates.

An explicit initialize() or main() function makes startup work visible to callers and tests. Import should not require host paths, network access or background workers for a definition-only module.

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 math

    Load or reuse the standard-library module.

  2. import math as again

    Bind another local name to the same normally cached module.

  3. print(math is again)

    Observe identity rather than assuming two imports create copies.

  4. print(math.sqrt(16))

    Run a function explicitly; merely importing did not call it.

Top-level statements run during initial loading and the resulting module is cached in sys.modules. A second ordinary import usually reuses it. Avoid opening files, making network requests or starting background workers merely because another module imports your definitions.

Conceptual cause and effect, not a live runtime trace

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

  1. Request nameImport first checks normal module-loading state and cache.
  2. Load if neededTop-level statements create the module's definitions and state.
  3. Reuse moduleLater normal imports bind names to the existing module object.
Predict before you run

What does math is again print?

Reuse a 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.

Use a different square.

Try: Replace sqrt(16) with sqrt(25).

Only the function result changes to 5.0; module identity remains shared.

Make local rebinding visible.

Try: Set again = None before the identity print.

Identity becomes False, but math remains the module; changing one local name does not edit the cache.

Before you move on

Two functions in one interpreter normally import json. Do they each receive an independent module namespace?

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 imports normally reuse one cached module object. Function-local import names can be separate bindings to that same module.

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

Break a cycle at the responsibility boundary

A circular dependency can expose a module before all its definitions have been created. Moving shared responsibilities below both callers removes that partial-initialization dependency.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Use explicit dependencies when two components appear to need each other. A cycle is about who needs which definitions and when, not merely spelling of imports.

Words you will see

Circular import
A dependency chain that returns to a module already being initialized.
Partial initialization
A module object exists but later top-level statements have not run yet.
Dependency injection
Passing a required collaborator explicitly instead of looking it up through a hidden import.

Separate a dependency from its caller

render receives fetch as a parameter. It does not import the storage module while storage is importing rendering code. The function can therefore be defined independently and called once the dependency is ready.

In the original cyclic arrangement, A might start importing B before A defines a symbol B requests. Python can expose A's existing but unfinished module, so that symbol is absent. Moving a common contract to a lower-level module can remove both directions.

Defer only for a reason

A function-local import delays loading until that function executes. It can be a justified narrow tool, but it does not magically remove architectural coupling; calling it too early may still find incomplete state.

Prefer extracting shared pure definitions or passing dependencies as here. Test the desired behavior without manipulating the global import cache or adding arbitrary folders to sys.path.

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 render(fetch):

    Declare the required behavior as an explicit parameter.

  2. return 'status: ' + fetch()

    Call the collaborator only when render runs.

  3. print(render(ready))

    Pass a function, not the already computed string, as the dependency.

Circular imports can observe partially initialized modules. Move shared contracts into a lower-level module, inject a dependency, or defer a narrow import when justified. Renaming a symptom does not fix a cyclic architecture.

Predict before you run

Does defining render immediately call fetch?

Pass a dependency explicitlyPYTHON 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.

Inject a different implementation.

Try: Add def waiting(): return 'waiting' and call render(waiting).

The new result is status: waiting without editing rendering's imports.

Observe a wrong boundary.

Try: Pass ready() instead of ready.

The string is not callable, so render raises TypeError when it tries fetch().

Before you move on

Two modules both need a data-only Status definition. Where could it live without making either module import the other?

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

In a lower-level shared module that imports neither caller. Both can depend downward on the definition without forming a cycle.

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

Keep script entry separate

A script entry guard runs an action only when the module's execution name is __main__, keeping reusable definitions available without that action on ordinary import.

READ / UNDERSTAND / THEN EXPERIMENT

Understand first

Use a main function plus a guard for small scripts that may also be imported by tests or other programs.

Words you will see

__name__
The execution name supplied to a module's namespace.
Entry point
The action chosen to begin a program.
Guard
A condition controlling whether a block runs.

Read the execution name

def main creates a function that returns 'ready'. The if compares __name__ with the string '__main__'. Script execution uses that name, so the guarded print calls main and displays its returned string.

Normal import uses the module's import name instead, so the guarded print is skipped. main still exists and callers can invoke it explicitly. The guard does not prevent other unguarded top-level code from running.

Keep work inside the action

Put resource opening, argument parsing and startup work behind main or another explicit function. That lets tests call behavior without performing startup merely by importing definitions.

A package entry module run with -m also uses the main execution role, but browser-local snippets are not a full command-line packaging environment. This example needs only a normal source namespace, with no file paths or subprocesses.

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 main():

    Define reusable behavior without yet running it.

  2. return 'ready'

    Produce a value when the function is called.

  3. if __name__ == '__main__':

    Check whether this namespace is being executed as the entry program.

  4. print(main())

    Run the guarded action and display ready.

Reusable definitions can be imported without running the script's entry action; execution as a script runs the guarded action.

Predict before you run

When run as the main program, what is printed?

Keep script entry separatePYTHON 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 the reusable return.

Try: Return 'waiting' from main.

The guarded print becomes waiting; the separation of definition and entry action remains.

Add explicit definition-only use.

Try: Remove the guard block and add print(main()).

It still prints ready in this snippet, but would now also print during ordinary import of that source.

Before you move on

When the same source executes with __name__ equal to 'sample', is main defined and is the guarded print run?

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

main is defined, but the print is skipped. The name comparison is false; the definition itself is outside the guard.

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

Where this idea earns its place

Module structure is an architectural dependency graph. Imports are executable steps in that graph, not merely textual inclusion. A library that opens connections or starts workers at import time makes tests and applications inherit hidden work before they have a chance to configure or validate anything.

Follow the mechanism step by step

Python locates a module, creates a module object, executes its top-level code and normally caches the result in sys.modules. During a circular import, another module may observe this partially initialized object before expected attributes exist. A later ordinary import usually reuses the cached module rather than rerunning initialization.

Work through a concrete application

Separate reusable definitions from script entry actions with a main guard. If two modules need each other's implementation, identify the shared lower-level contract or inject one dependency. A narrowly deferred import can be justified, but should not conceal an architectural cycle that future maintainers must rediscover.

Failure cases and misleading shortcuts

from module import value binds a name in the importing module. Rebinding module.value later does not update every previously imported binding. Reloading can therefore leave a mixture of old functions, classes and new state. A local file with a standard-library name can also shadow the intended dependency.

Cost, ownership and alternatives

Import side effects affect startup latency and reliability. Loading an optional heavy dependency only when its feature is used can be reasonable, provided missing support is reported explicitly. Avoid adding arbitrary untrusted paths to module search configuration; dependency resolution is part of the code-execution trust boundary.

Verify the contract

Test importing a package without network access, production settings or a particular working directory. Confirm it does not start background work or log secrets. For plugin registration, test duplicate names and isolated test runs. For packaging, test the installed artefact rather than only direct imports from the source checkout.

Transfer question: Why can a circular import fail only after an innocent refactor?

Changing which top-level statement executes first can expose a dependency on partially initialized module state. Fix the responsibility boundary or initialization ordering explicitly rather than relying on one fortunate import sequence.

RECALL BEFORE YOU SCROLL

Can you explain it?

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

Does a second ordinary import normally execute every top-level statement again?
TRANSFER THE IDEA

Rebuild: Keep script entry separate

Without copying the worked code, reproduce its observable contract: Reusable definitions can be imported without running the script's entry action; execution as a script runs the guarded action. 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

Read a module value without sharing its list

Capture the current integer-list module attribute into a fresh list, with an empty default for an absent attribute.

The contract

  • Input is a ModuleType object; values is either absent or a list of integers.
  • Return a fresh list equal to the current values, preserving order and duplicates. Missing values returns [].
  • Do not create attributes or mutate the module. Later module rebinding or nested list edits must not change the returned list.
Read a module value without sharing its listPYTHON 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. Module snapshot 1
    from types import ModuleType
    module = ModuleType('exercise_demo')
    module.values = [1, 2]
    before = dict(module.__dict__)
    result = read_values(module)
    assert type(result) is list and result == [1, 2] and module.__dict__ == before
    assert result is not getattr(module, 'values', None)
    result.append(99)
    assert module.__dict__ == before
    assert module.values == [1, 2]
    module.values = [8]
    assert result == [1, 2, 99]
  2. Module snapshot 2
    from types import ModuleType
    module = ModuleType('exercise_demo')
    module.values = []
    before = dict(module.__dict__)
    result = read_values(module)
    assert type(result) is list and result == [] and module.__dict__ == before
    assert result is not getattr(module, 'values', None)
    result.append(99)
    assert module.__dict__ == before
    assert module.values == []
    module.values = [8]
    assert result == [99]
  3. Module snapshot 3
    from types import ModuleType
    module = ModuleType('exercise_demo')
    module.values = [3, 3]
    before = dict(module.__dict__)
    result = read_values(module)
    assert type(result) is list and result == [3, 3] and module.__dict__ == before
    assert result is not getattr(module, 'values', None)
    result.append(99)
    assert module.__dict__ == before
    assert module.values == [3, 3]
    module.values = [8]
    assert result == [3, 3, 99]
  4. Module snapshot 4
    from types import ModuleType
    module = ModuleType('exercise_demo')
    module.values = [-1, 0]
    before = dict(module.__dict__)
    result = read_values(module)
    assert type(result) is list and result == [-1, 0] and module.__dict__ == before
    assert result is not getattr(module, 'values', None)
    result.append(99)
    assert module.__dict__ == before
    assert module.values == [-1, 0]
    module.values = [8]
    assert result == [-1, 0, 99]
  5. Module snapshot 5
    from types import ModuleType
    module = ModuleType('exercise_demo')
    module.values = [7]
    before = dict(module.__dict__)
    result = read_values(module)
    assert type(result) is list and result == [7] and module.__dict__ == before
    assert result is not getattr(module, 'values', None)
    result.append(99)
    assert module.__dict__ == before
    assert module.values == [7]
    module.values = [8]
    assert result == [7, 99]
  6. Module snapshot 6
    from types import ModuleType
    module = ModuleType('exercise_demo')
    before = dict(module.__dict__)
    result = read_values(module)
    assert type(result) is list and result == [] and module.__dict__ == before
    assert result is not getattr(module, 'values', None)
    result.append(99)
    assert module.__dict__ == before
    assert not hasattr(module, 'values')
    Why not return getattr directly?

    That would share the module's mutable list. The returned list is a snapshot of integer values, taking O(n) time and output space for n values, with no module-cache modification.

    GUIDED PRACTICE

    Run a fixed guarded source in a fresh namespace

    Model entry-name behavior without loading files, importing dynamic modules or editing sys.modules.

    The contract

    • Accept any execution-name string; treat only '__main__' as the entry role.
    • Return (events, namespace), an actual tuple containing a list and a fresh dict. Define callable main returning 'ready' in that dict.
    • events is ['ready'] for '__main__', otherwise []. Put that exact events list in namespace['events']; keep each invocation isolated.
    Run a fixed guarded source in a fresh namespacePYTHON 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. Entry role 1
      name = "__main__"
      a = run_guarded(name)
      b = run_guarded(name)
      assert type(a) is tuple and type(b) is tuple and len(a) == len(b) == 2
      events, namespace = a
      assert type(events) is list and events == ['ready'] and type(namespace) is dict
      assert namespace['__name__'] == name and namespace['events'] is events and callable(namespace['main'])
      assert type(namespace['main']()) is str and namespace['main']() == 'ready'
      assert namespace is not b[1] and events is not b[0] and name == "__main__"
    2. Entry role 2
      name = "demo"
      a = run_guarded(name)
      b = run_guarded(name)
      assert type(a) is tuple and type(b) is tuple and len(a) == len(b) == 2
      events, namespace = a
      assert type(events) is list and events == [] and type(namespace) is dict
      assert namespace['__name__'] == name and namespace['events'] is events and callable(namespace['main'])
      assert type(namespace['main']()) is str and namespace['main']() == 'ready'
      assert namespace is not b[1] and events is not b[0] and name == "demo"
    3. Entry role 3
      name = ""
      a = run_guarded(name)
      b = run_guarded(name)
      assert type(a) is tuple and type(b) is tuple and len(a) == len(b) == 2
      events, namespace = a
      assert type(events) is list and events == [] and type(namespace) is dict
      assert namespace['__name__'] == name and namespace['events'] is events and callable(namespace['main'])
      assert type(namespace['main']()) is str and namespace['main']() == 'ready'
      assert namespace is not b[1] and events is not b[0] and name == ""
    4. Entry role 4
      name = "package.worker"
      a = run_guarded(name)
      b = run_guarded(name)
      assert type(a) is tuple and type(b) is tuple and len(a) == len(b) == 2
      events, namespace = a
      assert type(events) is list and events == [] and type(namespace) is dict
      assert namespace['__name__'] == name and namespace['events'] is events and callable(namespace['main'])
      assert type(namespace['main']()) is str and namespace['main']() == 'ready'
      assert namespace is not b[1] and events is not b[0] and name == "package.worker"
    5. Entry role 5
      name = "__MAIN__"
      a = run_guarded(name)
      b = run_guarded(name)
      assert type(a) is tuple and type(b) is tuple and len(a) == len(b) == 2
      events, namespace = a
      assert type(events) is list and events == [] and type(namespace) is dict
      assert namespace['__name__'] == name and namespace['events'] is events and callable(namespace['main'])
      assert type(namespace['main']()) is str and namespace['main']() == 'ready'
      assert namespace is not b[1] and events is not b[0] and name == "__MAIN__"
    6. Entry role 6
      name = "main"
      a = run_guarded(name)
      b = run_guarded(name)
      assert type(a) is tuple and type(b) is tuple and len(a) == len(b) == 2
      events, namespace = a
      assert type(events) is list and events == [] and type(namespace) is dict
      assert namespace['__name__'] == name and namespace['events'] is events and callable(namespace['main'])
      assert type(namespace['main']()) is str and namespace['main']() == 'ready'
      assert namespace is not b[1] and events is not b[0] and name == "main"
      Why is this not an import loader?

      It executes one fixed source string in a fresh namespace. It models the guard but does not implement package discovery, trust, module caching or circular-import handling. The fixed source does constant-size work per call.

      TRANSFER / TRY BEFORE OPENING HINTS

      Transfer: schedule dependencies before callers

      Requirements changed: plan initialization order for a dependency graph rather than executing module definitions.

      The contract

      • Input is dict[str, list[str]], mapping each module to its dependencies; every referenced name is a key.
      • Return a new list in depth-first postorder, visiting roots in dictionary insertion order and dependency lists left to right; emit each name once.
      • On a cycle return None. Do not mutate any input list or dictionary. This models ordering only, not a real import loader; graphs are small and finite.
      Transfer: schedule dependencies before callersPYTHON 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. Dependency graph 1
        from copy import deepcopy
        graph = {'web': ['store'], 'store': []}
        before = deepcopy(graph)
        result = dependency_order(graph)
        assert type(result) is list and result == ['store', 'web'] and result is not graph
        assert graph == before
        other = dependency_order(graph)
        assert type(other) is list and other == result and other is not result and graph == before
      2. Dependency graph 2
        from copy import deepcopy
        graph = {}
        before = deepcopy(graph)
        result = dependency_order(graph)
        assert type(result) is list and result == [] and result is not graph
        assert graph == before
        other = dependency_order(graph)
        assert type(other) is list and other == result and other is not result and graph == before
      3. Dependency graph 3
        from copy import deepcopy
        graph = {'a': ['a']}
        before = deepcopy(graph)
        result = dependency_order(graph)
        assert type(result) is type(None) and result is None
        assert graph == before
        assert dependency_order(graph) is None and graph == before
        probe = {'ready': []}
        ordered = dependency_order(probe)
        assert type(ordered) is list and ordered == ['ready'] and ordered is not probe and probe == {'ready': []}
      4. Dependency graph 4
        from copy import deepcopy
        graph = {'a': ['b'], 'b': ['a']}
        before = deepcopy(graph)
        result = dependency_order(graph)
        assert type(result) is type(None) and result is None
        assert graph == before
        assert dependency_order(graph) is None and graph == before
        probe = {'ready': []}
        ordered = dependency_order(probe)
        assert type(ordered) is list and ordered == ['ready'] and ordered is not probe and probe == {'ready': []}
      5. Dependency graph 5
        from copy import deepcopy
        graph = {'a': ['c', 'c'], 'b': ['c'], 'c': []}
        before = deepcopy(graph)
        result = dependency_order(graph)
        assert type(result) is list and result == ['c', 'a', 'b'] and result is not graph
        assert graph == before
        other = dependency_order(graph)
        assert type(other) is list and other == result and other is not result and graph == before
      6. Dependency graph 6
        from copy import deepcopy
        graph = {'a': [], 'b': [], 'c': ['a']}
        before = deepcopy(graph)
        result = dependency_order(graph)
        assert type(result) is list and result == ['a', 'b', 'c'] and result is not graph
        assert graph == before
        other = dependency_order(graph)
        assert type(other) is list and other == result and other is not result and graph == before
        Why is a visited set alone not enough?

        A currently active node distinguishes a cycle from harmless reuse of a completed dependency. For v modules and e dependency references, this small recursive planner takes O(v + e) time and O(v) auxiliary space.

        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

        Names are cached separately

        Importing a name binds the object currently stored under that module attribute. Later rebinding the module attribute does not automatically rebind the imported local name.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Distinguish a live module lookup from a separately bound value when debugging stale configuration or mixed references after reload.

        Words you will see

        Attribute
        A named value accessed through an object with a dot.
        Rebinding
        Assigning a different object to an existing name.
        Reload
        Explicitly executing loading code again for a module, potentially leaving old external references.

        Use an in-memory module to expose the rule

        ModuleType creates a module object with an ordinary attribute namespace. bound = module.value models the binding performed by from module import value: bound refers to the current object, not a live link to the attribute slot.

        Replacing module.value with a new list leaves bound naming the old list. Appending to bound changes that old list. A fresh module.value lookup sees only the replacement.

        Mutation and rebinding are different

        If the module had mutated the original list instead of replacing its attribute, both references would observe that mutation because they shared one list. The stale-name issue appears when the attribute is rebound.

        Reload does not rewrite every object previously exported to callers. Prefer explicit configuration objects with clear update rules, or use module.attribute lookups when reading the current attribute is truly required. Do not present reload as a general production deployment strategy.

        The original example, step by step

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

        1. bound = module.value

          Retain the current list reference under another name.

        2. module.value = [2]

          Replace the attribute with a different list.

        3. bound.append(3)

          Mutate the old list that bound still names.

        4. print(module.value)

          A fresh lookup reads the new list [2].

        from module import value binds a name in the importing module. Later rebinding module.value does not automatically rebind every imported name. Reloading is not a general production update mechanism and can leave mixed old/new references.

        Predict before you run

        Why does bound contain 3 while module.value does not?

        Model a separately bound namePYTHON 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.

        Mutate rather than rebind.

        Try: Replace module.value = [2] with module.value.append(2).

        Both outputs become [1, 2, 3] because the shared list was never replaced.

        Read the current attribute again.

        Try: Set bound = module.value again after replacement.

        Both prints then show [2, 3]; the second binding selected the replacement list.

        Before you move on

        A module's list is imported as local_items, then the module appends to that same list. Does local_items see the append?

        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

        Yes. Both references still name one list. Replacing the module's list, rather than mutating it, is what separates their future lookups.

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

        Package structure and trust

        A module's name is part of an import lookup boundary. Avoid shadowing standard-library names or modifying search paths to find untrusted code.

        READ / UNDERSTAND / THEN EXPERIMENT

        Understand first

        Make package dependencies predictable. The browser-local exercise can model names and namespaces, but does not demonstrate installing packages or trusting host directories.

        Words you will see

        Shadowing
        Using a name that hides another available definition or module.
        Absolute import
        An import naming its top-level package explicitly.
        Package-relative import
        An import using leading dots to locate a sibling through its known package context.

        A local binding can hide your imported tool

        The json module is first retained as json_tool. Later json is a string in this local namespace. Calling json_tool.dumps still works because that name keeps the module, not because Python guessed the intended meaning of json.

        A project file named json.py can cause a different form of shadowing during import resolution. Prefer domain-specific filenames and explicit package structure. Aliasing a local name cannot make an untrusted imported module safe.

        Do not repair lookup by widening trust

        Use deliberate package imports rather than inserting arbitrary user-controlled directories into sys.path. A leading dot expresses a known package relationship, not a generic promise to find a neighboring host file in every execution mode.

        This snippet only uses an already available standard-library module and local bindings. Real packaging and environment installation belong in a separate local lab. No filesystem layout or host-specific path is assumed here.

        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 json as json_tool

          Choose an unambiguous local name for the module.

        2. json = 'a local label'

          Bind a separate string without changing json_tool.

        3. print(json_tool.dumps({'ok': True}, sort_keys=True))

          Use the retained module and request deterministic key order.

        4. print(json_tool.__name__)

          The local alias did not rename the actual module.

        Use package-relative imports deliberately and avoid names that shadow standard-library modules. Import paths and installed dependencies are part of the trust boundary. Do not add arbitrary user-controlled directories to sys.path.

        Predict before you run

        Does importing json as json_tool change the module's __name__?

        Keep a module binding explicitPYTHON 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 another label.

        Try: Change the local json string to 'report'.

        Only the first printed line changes; json_tool remains usable.

        Add another serialized field.

        Try: Serialize {'z': 1, 'a': 2} with sort_keys=True.

        The JSON is {"a": 2, "z": 1}; explicit sorting controls display rather than relying on input order.

        Before you move on

        A project adds a file called random.py and then its old import random behaves differently. Is increasing import privileges the right first fix?

        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. Investigate name shadowing and package structure. Rename the conflicting project module deliberately; do not widen the import trust boundary.

        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.