Skip to main content

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.

L1

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.py ideas live in the stdlib math module) 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.hammer opens that drawer and lets you use hammer.
FormMeaningExample
import modBind module objectimport math; math.sqrt(9)
import mod as mAlias the moduleimport numpy as np
from mod import nameBind a name directlyfrom math import sqrt
from mod import name as nAlias a namefrom datetime import datetime as dt
from mod import *Import public namesAvoid 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__.py and span multiple directories on sys.path.
  • Packages nest: pkg.subpkg.mod maps to pkg/subpkg/mod.py.
TermFilesystemImport name
Moduleutil.pyutil
Packageshop/ + __init__.pyshop
Submoduleshop/cart.pyshop.cart
Subpackageshop/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.

Python modules and packages infographic: module as a single util.py file, package as a shop folder with __init__.py and submodules, plus a shop example showing project tree, cart.py Cart class, __init__ re-export, and main.py imports.
Modules & packages — util.py vs shop/, with a working import example
  • Module: one file — import util then util.helper().
  • Package: folder + __init__.py — from shop.cart import Cart.
  • Example: shop/cart.py defines Cart; main.py imports and uses it.
  • Tip: prefer absolute imports; run with python main.py or python -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.module runs 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).
StatementMeaning
from . import siblingImport sibling module in same package
from .sibling import nameImport a name from sibling
from .. import parent_modGo up one package level
from shop.cart import CartAbsolute import from project root package

__all__ and star imports

  • __all__ lists names exported by from 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.
PathPurpose
pyproject.toml / requirements.txtDependencies and build metadata
src/mypkg/__init__.pyPackage root
src/mypkg/api.pyLibrary code
tests/test_api.pyTests
README.mdHuman docs
L2

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__.py can still form a package if found on sys.path.
  • Useful for plugin ecosystems split across distributions.
  • Regular packages with __init__.py are simpler for beginners and most apps.

Executable packages

  • Add __main__.py inside a package to support python -m mypkg.
  • Console entry points in packaging metadata expose CLI commands after install.

Module attributes worth knowing

AttributeMeaning
__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.
L3

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.

L4

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]))
L5

Problem Solving Tricks

  • Prefer absolute imports in application code for readability.
  • Use python -m pytest / python -m mypkg so package context stays correct.
  • Guard scripts with if __name__ == "__main__":.
  • Avoid from module import * outside carefully designed package APIs.
  • When debugging imports, print __file__ and sys.path[0].
  • Put shared types in a third module to break circular imports.
  • Keep __init__.py thin: re-export, do not hide heavy side effects.
  • Editable installs (pip install -e .) beat manual sys.path hacks.
  • 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.
L6

Practice Programs List

  1. Create a package shapes with circle.py and rectangle.py plus a clean __init__.py API.
  2. Add __main__.py so python -m shapes prints a help line.
  3. Write a plugin loader using importlib.import_module and a list of module name strings.
  4. Demonstrate import * with and without __all__.
  5. Cause a circular import on purpose, then fix it by extracting a shared module.
  6. Compare running python shop/cart.py vs python -m shop.cart with a relative import.
  7. Print sys.path before and after pip install -e . in a practice project.
  8. Use importlib.reload after editing a module file and observe refreshed behavior.
  9. Organize a mini project with src/mypkg layout and one test importing it.
  10. Document your public API with __all__ in every user-facing module.
  11. Explore a namespace package by creating two folders with the same top name on sys.path.
  12. Rewrite a script that uses ad-hoc sys.path.insert into a proper package import.