1.3.1Python Intermediate

Modules — import, from…import, as aliasing

1,923 words9 min readdifficulty · medium

WHY do modules exist?


WHAT actually happens on import

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

HOW to import — the four forms

Form 1: import module

import math
print(math.pi)        # 3.14159...
print(math.sqrt(16))  # 4.0

Form 2: from module import name

from math import pi, sqrt
print(pi)        # no prefix needed
print(sqrt(16))  # 4.0

Form 3: import module as alias

import numpy as np
np.array([1, 2, 3])

Form 4: from module import name as alias

from datetime import datetime as dt
now = dt.now()

Used to avoid a clash (here the module datetime and the class datetime share a name).


WHERE does Python look? (sys.path)


Worked examples


Recall Feynman: explain it to a 12-year-old (click to open)

Imagine your toy box has a calculator toy inside (math). You can say "toy box, give me your calculator" (import math, then math.sqrt) — you keep saying "toy box's" before every toy so you don't mix it with your own toys. Or you can take the calculator out and put it on your desk (from math import sqrt) so you grab it directly — but careful, now if you already had a thing called "calculator" on your desk, the new one covers it up! And as is just sticking a nickname sticker on the toy so you can call it something shorter.


Flashcards

What is a Python module?
A single .py file containing reusable code (functions, classes, variables).
What is the difference between a module and a package?
A module is one .py file; a package is a folder of modules containing an __init__.py.
After import math, how do you call sqrt?
math.sqrt(...) — you must use the math. prefix.
After from math import sqrt, how do you call sqrt?
Just sqrt(...) — the name was copied into your namespace, no prefix.
What does as do in an import?
Gives the imported module/name an alias (nickname) — same object, shorter label.
Why is from module import * discouraged?
It dumps all public names into your namespace, hiding origins and silently overwriting your own variables.
How many times does Python execute a module's top-level code on repeated imports?
Once — subsequent imports are served from the sys.modules cache.
Where does Python search for a module to import?
The folders listed in sys.path (script dir, PYTHONPATH, then standard/installed libs), first match wins.
Why does naming your file random.py break import random?
Your local file is found first on sys.path and shadows the real standard-library module.
What is a namespace in the context of modules?
A container of names; import module keeps the module's names behind its prefix so they don't clash with yours.

Connections

  • Python Functions — modules mostly bundle reusable functions.
  • Namespaces and Scope — import is fundamentally about binding names into namespaces.
  • sys and os modulessys.path and sys.modules control import resolution.
  • Packages and __init__.py — scaling from one file to many.
  • Virtual Environments and pip — how third-party modules get onto sys.path.
  • DRY Principle — the design idea that motivates modules.

Concept Map

motivates

grouped into

provides

runs file once

has form

has form

has form

has form

keeps

can cause

shortens name

avoids

DRY principle

Module = one py file

Package = folder + init

Namespace

import statement

import module

from module import name

import module as alias

from module import name as alias

sys.modules cache

Name clash risk

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, ek module matlab simple — ek .py file jisme pehle se likha hua code (functions, variables, classes) pada hota hai. import ka kaam hai woh code apni file me udhaar lena, taaki tumhe dobara likhna na pade. Jaise library se book reference lete ho — poori book copy nahi karte, bas naam se mangwa lete ho. Yahi DRY principle hai: Don't Repeat Yourself.

Char tareeke hote hain. import math karoge to har cheez ke aage math. lagana padega (math.pi) — isse tumhare apne naam aur module ke naam kabhi clash nahi karte, safe rehta hai. from math import pi karoge to seedha pi use kar sakte ho bina prefix ke — convenient, par dhyan rakho, agar tumne baad me khud pi banaya to purana overwrite ho jayega. import numpy as np matlab nickname — same cheez, bas chhota naam (community standard: np, pd, plt).

Ek important baat: jab tum import karte ho, Python pehle file dhoondhta hai sys.path me, phir uska top-level code ek hi baar chalata hai, aur cache (sys.modules) me rakh leta hai. Isliye do baar import karne par code dobara nahi chalta. Aur yahi reason hai ki apni file ka naam random.py mat rakhna — warna tumhari file pehle mil jayegi aur asli random module chhup jayega. from module import * se bacho — yeh sab naam ek saath ghusa deta hai aur confusion + overwrite ka khatra hota hai. Explicit import sabse safe aur readable hai.

Go deeper — visual, from zero

Test yourself — Python Intermediate

Connections