Modules
corebeginnerA module is just a `.py` file. `import mathy` runs mathy.py once and binds the name `mathy` to the resulting namespace object, so every name mathy.py defined is reachable as mathy.something.
Think of it as
A module is a box that gets sealed the moment its file finishes running. import does not hand you the source code to re-read — it hands you the sealed box, labeled with the module name, holding whatever the file assigned at the top level while it ran.
What we're doing: Import a module two different ways and show that both paths reach the same underlying object.
- 1
- mathy.py has nothing marking it as importable — any .py file qualifies.
- 10
- import mathy runs the whole file once and binds the name mathy to what it produced.
- 11
- from mathy import area as circle_area reaches into that same run and binds one name directly, renamed.
- 13
- mathy.area and circle_area are the exact same function object — two names, one function.
12.56636
12.56636
3.14159Why this works: import mathy executes mathy.py exactly once, top to bottom, and collects every name the file assigned at module level into one namespace object bound to mathy. from mathy import area as circle_area runs the same file (or reuses the cached run — see the import caching concept) and then reaches directly into that namespace for area, binding it locally under a new name. Both mathy.area and circle_area point at the identical function object, which is why calling either gives the identical result.
Assuming a module's names appear on their own, without importing it
Wrong
Better
What you see: NameError: name 'mathy' is not defined — the file exists on disk, but nothing has run it yet.
Why: A .py file sitting in a directory is not automatically part of the running program — Python only executes it, and creates the namespace object for it, in response to an explicit import statement. Being importable and being imported are different things; the file has to actually be imported before any of its names exist in the current scope.
- mathy.py — PI = 3.14159, def area(r): ...
- import mathy — the file runs, top to bottom, once
- mathy — a namespace: mathy.PI, mathy.area
Ways to bring a module — or a name from it — into scope
Together
Remember: import runs a .py file once and hands back a namespace object — mathy.thing reaches into it; from mathy import thing skips the prefix.
See also: packages · imports · import resolution

