1.3.1 · D3Python Intermediate

Worked examples — Modules — import, from…import, as aliasing

2,348 words11 min readBack to topic

Before a single line of code: an import is a binding. It takes a name (like math) and points it at an object in your namespace — the container of names your file owns. Every scenario below is really the question "which name now points at what?"


The scenario matrix

Every import situation falls into one of these cells. The examples that follow each carry a tag like [Cell A] so you can check off the whole grid.

Cell Case class What could go wrong / matter
A Plain import module Must use the module. prefix every time
B from module import name Name copied in — no prefix, but risk of overwrite
C import module as alias Same object, shorter label
D from module import name as alias Fix a name clash
E Shadowing bug (from … import overwrites your name) Silent wrong answer
F Local file shadows stdlib (random.py) import finds the wrong file
G "Runs once" — repeated import + cache Side-effects fire exactly once
H Degenerate: importing a missing module ModuleNotFoundError
I Real-world word problem Choosing the right form
J Exam twist: import a.b.c sub-modules What name actually gets bound?

We will hit all ten cells in the examples below.


Worked examples

Figure — Modules — import, from…import, as aliasing
Figure — Modules — import, from…import, as aliasing


Recall Quick self-check (click to open)

After import math as m, does the name math exist? ::: No — only m is bound; math would raise NameError. After from math import sqrt, then def sqrt(n): return n*n, what does sqrt(16) give? ::: 256 — your definition silently rebinds the name. How many times does a module's top-level print fire across two imports? ::: Once — the second import is served from sys.modules. After import os.path, is the bare name path bound? ::: No — only os is bound; use os.path or from os import path. What error does importing a missing module raise? ::: ModuleNotFoundError.


Connections

  • Modules — import, from…import, as aliasing (index 1.3.1) — the parent note these examples drill.
  • Namespaces and Scope — why the last binding of a name wins (Cells E, J).
  • sys and os modulessys.path search order behind Cell F.
  • Packages and __init__.py — dotted sub-module imports (Cell J).
  • Virtual Environments and pip — installing missing libraries (Cell H).
  • DRY Principle — the reason selective imports keep code readable (Cell I).