Introduction & Syntax
Modules and Packages · Study material
A module is simply a .py file; a package is a folder of modules. Modules let you split a program into files, reuse code across projects and use the huge standard library – math, datetime, json, collections and hundreds more – plus third-party packages installed with pip. Interviews ask how import finds and caches modules, what __name__ == "__main__" does, the difference between import x and from x import y, relative imports and __init__.py. This topic answers them with examples that really run, then gives you 50 practice questions run on Python 3.
On this page
- Import forms: import, from … import, as, import *
- Writing your own module and the __main__ guard
- How imports are found (sys.path) and cached (sys.modules)
- Packages, __init__.py, absolute and relative imports
- __all__, dir() and help()
- Standard library essentials, pip and virtual environments
Ways to import
| Form | What you get | Usage |
|---|---|---|
import math | the module object | math.sqrt(9) |
from math import sqrt | one name, copied into your namespace | sqrt(9) |
import numpy as np | the module under a short alias | np.array(...) |
from math import sqrt as root | a renamed name | root(9) |
from math import * | all public names – avoid: unclear origin, may shadow your names | sqrt(9) |
import math # the whole module: use math.name
from math import sqrt, pi # specific names into this namespace
from statistics import mean as avg # rename with as
import datetime as dt # module alias
print(math.floor(7.8), sqrt(81), round(pi, 3))
print(avg([70, 80, 90]))
print(dt.date(2026, 11, 30).strftime("%A"))
print(type(math).__name__, math.__name__)
7 9.0 3.142 80 Monday module math
Writing your own module
Save functions in lf_geometry.py and any file in the same folder (or on sys.path) can import lf_geometry. The module's top-level code runs once, at the first import. When a file is run directly its __name__ is "__main__"; when imported it is the module name – so put test or demo code under if __name__ == "__main__":. Names starting with an underscore are internal by convention. (The example writes the module to a temporary folder so that it can run here as one file.)
import sys, tempfile, textwrap, pathlib
folder = pathlib.Path(tempfile.mkdtemp())
# Any .py file is a module. Write one: lf_geometry.py
(folder / "lf_geometry.py").write_text(textwrap.dedent('''
"""Simple geometry helpers."""
PI = 3.14159
def circle_area(r):
return round(PI * r * r, 2)
def _helper(): # leading underscore: "internal" by convention
return "hidden"
if __name__ == "__main__": # runs only when the file itself is executed
print("testing geometry")
'''))
sys.path.insert(0, str(folder)) # let Python find modules in that folder
import lf_geometry
print(lf_geometry.circle_area(2))
print(lf_geometry.__name__, lf_geometry.__doc__)
print([n for n in dir(lf_geometry) if not n.startswith("__")])
12.57 lf_geometry Simple geometry helpers. ['PI', '_helper', 'circle_area']
How imports are found and cached
import x first checks sys.modules, the cache of already-loaded modules; only if x is not there does Python search the folders in sys.path – the script's folder, PYTHONPATH, the standard library and site-packages – load the file and run it. Importing again returns the cached module without running its code. importlib.reload(module) re-executes the file. Never name your own file like a standard module (random.py, math.py, json.py): it would be found first and hide the real one.
import sys, tempfile, pathlib, importlib
folder = pathlib.Path(tempfile.mkdtemp())
(folder / "lf_config.py").write_text('print("loading lf_config")\nMODE = "dev"\n')
sys.path.insert(0, str(folder))
import lf_config # runs the module's code: prints once
import lf_config # already in sys.modules: nothing runs again
print("lf_config" in sys.modules, lf_config.MODE)
lf_config.MODE = "prod" # module attributes can be changed at run time
importlib.reload(lf_config) # reload re-executes the file
print(lf_config.MODE)
loading lf_config True dev loading lf_config dev
Packages
A package is a folder of modules, optionally with an __init__.py that runs when the package is imported (and can expose convenient names). Inside a package, modules can import each other with relative imports (from .pricing import with_gst, from .. import x); from outside, use absolute imports such as from lf_shop.payments.upi import pay. Relative imports work only in modules that belong to a package – not in a script run directly.
import sys, tempfile, pathlib
root = pathlib.Path(tempfile.mkdtemp())
pkg = root / "lf_shop"
(pkg / "payments").mkdir(parents=True)
(pkg / "__init__.py").write_text('VERSION = "1.0"\nfrom .cart import total\n')
(pkg / "cart.py").write_text(
"from .pricing import with_gst\n" # relative import inside the package
"def total(prices):\n return with_gst(sum(prices))\n")
(pkg / "pricing.py").write_text("def with_gst(amount):\n return round(amount * 1.18, 2)\n")
(pkg / "payments" / "__init__.py").write_text("")
(pkg / "payments" / "upi.py").write_text('def pay(amount):\n return f"Paid Rs {amount} by UPI"\n')
sys.path.insert(0, str(root))
import lf_shop
from lf_shop.payments.upi import pay # absolute import of a sub-package module
print(lf_shop.VERSION, lf_shop.total([100, 250]))
print(pay(413.0))
1.0 413.0 Paid Rs 413.0 by UPI
The standard library
Python ships "batteries included". A few modules worth knowing well: math and statistics for numbers, random and secrets for random values, datetime for dates, collections (Counter, defaultdict, deque, namedtuple), itertools (combinations, permutations, accumulate, groupby), functools (lru_cache, partial, reduce), json and csv for data files, os, pathlib and shutil for files, re for regular expressions, and sys for the interpreter.
import math, statistics, json
from collections import Counter, defaultdict, deque
from itertools import combinations, accumulate
from datetime import date, timedelta
from pathlib import PurePosixPath
print(math.gcd(84, 36), math.isqrt(50), math.comb(5, 2))
print(statistics.median([7, 1, 5, 3]), Counter("banana").most_common(1))
print(list(combinations("ABC", 2)), list(accumulate([1, 2, 3, 4])))
print(date(2026, 12, 25) - date(2026, 11, 30), date(2026, 11, 30) + timedelta(days=45))
print(json.dumps({"name": "Asha", "skills": ["python", "sql"]}))
p = PurePosixPath("reports") / "2026" / "marks.csv"
print(p, p.suffix, p.stem)
12 7 10
4.0 [('a', 3)]
[('A', 'B'), ('A', 'C'), ('B', 'C')] [1, 3, 6, 10]
25 days, 0:00:00 2027-01-14
{"name": "Asha", "skills": ["python", "sql"]}
reports/2026/marks.csv .csv markspip and virtual environments
Third-party packages come from PyPI. Create an isolated virtual environment per project so that each has its own package versions, then install with pip:
python -m venv .venv # create the environment in the folder .venv
source .venv/bin/activate # activate (Windows: .venv\Scripts\activate)
pip install requests pandas # install packages into this environment only
pip freeze > requirements.txt # record exact versions
pip install -r requirements.txt # recreate the same environment elsewhere
deactivate # leave the environment
Common mistakes
- Naming a file random.py or math.py – it hides the standard module.
- import math, then sqrt(9) – NameError; write math.sqrt or from math import sqrt.
- from module import * – unclear names; can shadow built-ins (os exports open).
- Assigning to a module name – math = 3.14 replaces the module.
- Test code without a __main__ guard – it runs on every import.
- Relative imports in a script – ImportError: no known parent package.
- Editing a module and importing again – the cached version is used; reload or restart.
Key points to remember
- A module is a .py file; a package is a folder of modules.
- A module's code runs once, on first import; later imports use sys.modules.
- Python searches sys.path in order – the script's folder first.
- __name__ is "__main__" only for the file being run.
- __init__.py runs when its package is imported.
- Relative imports (from . import x) work only inside packages.
- __all__ lists what from module import * brings in.
Frequently asked questions
Is __init__.py required?
Not since Python 3.3 – a folder without it is a "namespace package". Adding it is still the norm: it marks a regular package and lets you run setup code or re-export names.
What is the difference between a module, a package and a library?
A module is one file, a package is a folder of modules, and "library" is an informal word for a collection of packages you install and use (such as requests or pandas).
Where are installed packages stored?
In the site-packages folder of the active environment; python -m site or pip show package-name shows the location.
Where can I learn more?
Read Python Modules, pip and Virtual Environments and The Python Standard Library in the Python tutorial, then practise with the exercises below.