Modules & Files
Modules & Packages
Complete lesson for Modules & Packages using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.
Basics — Modules & Packages
Section: Modules & Files. Modules and packages in Python — import forms, module search path, packages with __init__.py, relative imports, and structuring a project.
What is a module?
- A module is a Python file (
math.pyideas live in the stdlibmathmodule) whose top-level names become attributes after import. - Import executes the file once, caches it in
sys.modules, and reuses that object on later imports. - Real-life analogy: a toolbox drawer —
import toolshed.hammeropens that drawer and lets you usehammer.
| Form | Meaning | Example |
|---|---|---|
import mod | Bind module object | import math; math.sqrt(9) |
import mod as m | Alias the module | import numpy as np |
from mod import name | Bind a name directly | from math import sqrt |
from mod import name as n | Alias a name | from datetime import datetime as dt |
from mod import * | Import public names | Avoid in library code |
What is a package?
- A package is a directory of modules, traditionally with
__init__.py(regular package). - Namespace packages (PEP 420) can omit
__init__.pyand span multiple directories onsys.path. - Packages nest:
pkg.subpkg.modmaps topkg/subpkg/mod.py.
| Term | Filesystem | Import name |
|---|---|---|
| Module | util.py | util |
| Package | shop/ + __init__.py | shop |
| Submodule | shop/cart.py | shop.cart |
| Subpackage | shop/payments/ | shop.payments |
Modules vs packages — shop example
A module is one .py file. A package is a
folder of modules (usually with __init__.py). The poster below contrasts
both ideas, then walks a small shop package: tree layout, Cart
in cart.py, and imports from main.py.
util.py vs shop/, with a working import example
- Module: one file —
import utilthenutil.helper(). - Package: folder +
__init__.py—from shop.cart import Cart. - Example:
shop/cart.pydefinesCart;main.pyimports and uses it. - Tip: prefer absolute imports; run with
python main.pyorpython -m shop.
Module search path (sys.path)
- Import looks through
sys.path: script directory (or""),PYTHONPATH, and standard library / site-packages. sys.path.insert(0, path)can add a folder for demos; prefer proper installs / editable installs for real projects.- A wrong working directory is a common "ModuleNotFoundError" cause.
import sys
from pathlib import Path
print("entries:", len(sys.path))
print("first:", sys.path[0] or "(empty = cwd)")
print("stdlib sample:", Path(sys.prefix)) __name__ and python -m
- When a file is run as the main program,
__name__ == "__main__". - When imported,
__name__is the module’s dotted name. python -m package.moduleruns a module with its package context (relative imports work).
def main() -> None:
print("running as", __name__)
if __name__ == "__main__":
main() __init__.py role
- Marks a regular package and runs on first import of the package.
- Often re-exports a clean public API:
from .cart import Cart. - Can stay empty; emptiness still makes a regular package.
Absolute vs relative imports
- Absolute:
from shop.cart import Cart— clear and preferred in most app code. - Relative:
from .cart import Cart,from ..utils import helpers— good inside packages. - Relative imports only work inside a package (not in a loosely run script without package context).
| Statement | Meaning |
|---|---|
from . import sibling | Import sibling module in same package |
from .sibling import name | Import a name from sibling |
from .. import parent_mod | Go up one package level |
from shop.cart import Cart | Absolute import from project root package |
__all__ and star imports
__all__lists names exported byfrom module import *.- Without
__all__,import *takes public names (no leading underscore). - Library style: avoid
import *in production modules; use it only in REPLs or__init__re-exports carefully.
# inside a demo module conceptually:
__all__ = ["public_fn"]
def public_fn():
return "ok"
def _helper():
return "hidden" Project layout sketch
- Put importable packages under
src/or the repo root; keep scripts thin. - One package name matching your project (
learncodeguru/). - Tests import the package the same way users will.
| Path | Purpose |
|---|---|
pyproject.toml / requirements.txt | Dependencies and build metadata |
src/mypkg/__init__.py | Package root |
src/mypkg/api.py | Library code |
tests/test_api.py | Tests |
README.md | Human docs |
Advanced — Modules & Packages
importlib dynamic import
importlib.import_module("pkg.mod")loads a module from a string — useful for plugins.importlib.reload(mod)re-executes a module (careful with existing object references).
import importlib
import math
mod = importlib.import_module("math")
print(mod.sqrt(16))
math = importlib.reload(math)
print("reloaded", math.__name__) Circular imports
- A imports B while B imports A → partial initialization and
ImportError/ attribute errors. - Fixes: redesign boundaries, import inside functions, or extract shared types to a third module.
Namespace packages (PEP 420)
- Directories without
__init__.pycan still form a package if found onsys.path. - Useful for plugin ecosystems split across distributions.
- Regular packages with
__init__.pyare simpler for beginners and most apps.
Executable packages
- Add
__main__.pyinside a package to supportpython -m mypkg. - Console entry points in packaging metadata expose CLI commands after install.
Module attributes worth knowing
| Attribute | Meaning |
|---|---|
__name__ | Dotted module name or "__main__" |
__file__ | Path to the source file (if any) |
__package__ | Package name for relative imports |
__doc__ | Module docstring |
__all__ | Public export list for import * |
Packaging vs modules (big picture)
- A module/package is a language concept (
import). - Distribution packaging (
pip install, wheels) is how you share those modules. - You can import a local package without publishing it — path and layout matter.
Tricky Interview Points
Q1) What is the difference between a module and a package?
Answer A module is typically a single .py file. A package is a directory of modules (often with __init__.py) importable via dotted names.
Q2) What does import do internally?
Answer Finds the module on sys.path, loads/executes it once, caches it in sys.modules, and binds the name in the importer’s namespace.
Q3) Why use if __name__ == "__main__"?
Answer So library code is not executed on import, while the file remains runnable as a script.
Q4) Absolute vs relative imports?
Answer Absolute uses the full package path. Relative uses leading dots and only works inside a package context.
Q5) What is __init__.py for?
Answer It marks a regular package and runs on package import; often used to expose a public API.
Q6) What is sys.path?
Answer The list of directories/zip files Python searches when importing modules.
Q7) What does from module import * use?
Answer Names in __all__ if defined; otherwise public names not starting with an underscore.
Q8) How do you run a package as a program?
Answer python -m package or python -m package.module, often backed by __main__.py.
Q9) How do you fix circular imports?
Answer Refactor shared code into a third module, delay imports inside functions, or rethink dependencies.
Q10) What is importlib used for?
Answer Programmatic import, reload, and custom loaders — e.g. plugins loaded by name string.
Q11) What is a namespace package?
Answer A PEP 420 package that may omit __init__.py and can be split across multiple directories on sys.path.
Q12) Why does ModuleNotFoundError happen for a file that exists?
Answer Usually the package root is not on sys.path, the working directory is wrong, or the script was run in a way that breaks package context for relative imports.
Simple Programs
Create a tiny package on disk and import it
import sys
from pathlib import Path
root = Path("demo_pkg_root")
pkg = root / "greetings"
pkg.mkdir(parents=True, exist_ok=True)
(pkg / "__init__.py").write_text(
"from .hello import shout\n__all__ = ['shout']\n",
encoding="utf-8",
)
(pkg / "hello.py").write_text(
"def shout(name: str) -> str:\n return f'Hello, {name}!'\n",
encoding="utf-8",
)
sys.path.insert(0, str(root.resolve()))
from greetings import shout # noqa: E402
print(shout("Python"))
print("package file:", Path(sys.modules["greetings"].__file__).name) Demonstrate __name__ as script vs import
import importlib.util
from pathlib import Path
path = Path("sample_mod.py")
path.write_text(
'VALUE = 42\n'
'def show():\n'
' print("name=", __name__, "value=", VALUE)\n'
'if __name__ == "__main__":\n'
' show()\n',
encoding="utf-8",
)
spec = importlib.util.spec_from_file_location("sample_mod", path)
mod = importlib.util.module_from_spec(spec)
assert spec.loader is not None
spec.loader.exec_module(mod)
mod.show() # name= sample_mod Inspect sys.modules and sys.path
import sys
import math
print("math cached:", "math" in sys.modules)
print("math file:", getattr(math, "__file__", None))
print("path entries showing site-packages:")
for p in sys.path:
if "site-packages" in p.replace("\\", "/"):
print(" ", p)
break
else:
print(" (none matched in this environment)") importlib.import_module by string
import importlib
for name in ("math", "json", "pathlib"):
mod = importlib.import_module(name)
print(name, "->", mod.__name__) Package __all__ re-export pattern
from pathlib import Path
import sys
root = Path("api_pkg_root")
pkg = root / "api"
pkg.mkdir(parents=True, exist_ok=True)
(pkg / "ops.py").write_text(
"def add(a, b):\n return a + b\n\ndef _private():\n return 'secret'\n",
encoding="utf-8",
)
(pkg / "__init__.py").write_text(
"from .ops import add\n__all__ = ['add']\n",
encoding="utf-8",
)
sys.path.insert(0, str(root.resolve()))
import api
print(api.add(2, 3))
print("all:", api.__all__) Relative-import style layout (simulated)
from pathlib import Path
import sys
root = Path("rel_demo")
pkg = root / "shop"
pkg.mkdir(parents=True, exist_ok=True)
(pkg / "__init__.py").write_text("", encoding="utf-8")
(pkg / "tax.py").write_text(
"def with_tax(x):\n return round(x * 1.18, 2)\n",
encoding="utf-8",
)
(pkg / "cart.py").write_text(
"from .tax import with_tax\n"
"def total(prices):\n"
" return with_tax(sum(prices))\n",
encoding="utf-8",
)
sys.path.insert(0, str(root.resolve()))
from shop.cart import total
print(total([100, 50])) # 177.0 List public names of a stdlib module
import math
public = [n for n in dir(math) if not n.startswith("_")]
print("count:", len(public))
print("sample:", ", ".join(public[:8])) Problem Solving Tricks
- Prefer absolute imports in application code for readability.
- Use
python -m pytest/python -m mypkgso package context stays correct. - Guard scripts with
if __name__ == "__main__":. - Avoid
from module import *outside carefully designed package APIs. - When debugging imports, print
__file__andsys.path[0]. - Put shared types in a third module to break circular imports.
- Keep
__init__.pythin: re-export, do not hide heavy side effects. - Editable installs (
pip install -e .) beat manualsys.pathhacks. - Name packages after your product; avoid colliding with stdlib names (
email,test,random). - Remember: import executes module-level code — keep side effects out of import time.
Practice Programs List
- Create a package
shapeswithcircle.pyandrectangle.pyplus a clean__init__.pyAPI. - Add
__main__.pysopython -m shapesprints a help line. - Write a plugin loader using
importlib.import_moduleand a list of module name strings. - Demonstrate
import *with and without__all__. - Cause a circular import on purpose, then fix it by extracting a shared module.
- Compare running
python shop/cart.pyvspython -m shop.cartwith a relative import. - Print
sys.pathbefore and afterpip install -e .in a practice project. - Use
importlib.reloadafter editing a module file and observe refreshed behavior. - Organize a mini project with
src/mypkglayout and one test importing it. - Document your public API with
__all__in every user-facing module. - Explore a namespace package by creating two folders with the same top name on
sys.path. - Rewrite a script that uses ad-hoc
sys.path.insertinto a proper package import.