Python Modules
A module is simply a Python file (.py) containing functions, classes, and variables that can be imported and
reused in other programs. Modules are the foundation of Python's don't repeat yourself philosophy —
write code once, import it everywhere. This chapter covers every import form, the critical __name__ == '__main__' guard, Python's rich standard library, and how to
create and structure your own custom modules like a professional.
What is a Module?
A module is any Python file (.py
extension) that contains Python code. Every Python file you write is automatically a module. Modules let you
organise code into reusable, maintainable units — instead of one enormous script, you break your project into
focused files and import what you need.
sys.modules, and reuses it on subsequent
imports# Every .py file IS a module
# ── File: mymath.py ──────────────────────────────────
PI = 3.14159 # module-level constant
def add(a, b):
"""Return sum of a and b."""
return a + b
def circle_area(r):
"""Return area of circle with radius r."""
return PI * r * r
# ── File: main.py (imports mymath) ───────────────────
import mymath
print(mymath.PI) # 3.14159
print(mymath.add(3, 4)) # 7
print(mymath.circle_area(5)) # 78.53975
# Module is cached after first import
import mymath # ← no re-execution; returns cached version
import sys
print("mymath" in sys.modules) # True
All Import Forms
Python offers several ways to import — each with its own use case. Choosing the right form affects readability, namespace pollution, and performance.
# ── Form 1: import module ─────────────────────────────
import math
print(math.sqrt(16)) # 4.0 — must prefix with module name
print(math.pi) # 3.141592653589793
# ── Form 2: from module import name ──────────────────
from math import sqrt, pi
print(sqrt(25)) # 5.0 — no prefix needed
print(pi) # 3.141592653589793
# ── Form 3: import module as alias ───────────────────
import numpy as np # industry-standard alias
import pandas as pd
import datetime as dt
today = dt.date.today()
# ── Form 4: from module import name as alias ─────────
from math import factorial as fact
print(fact(6)) # 720
# ── Form 5: from module import * (discouraged) ───────
from math import * # imports ALL public names
print(sin(0)) # 0.0 — no prefix needed
# ❌ Avoid — pollutes namespace, hides origin of names
# ── Importing submodules ──────────────────────────────
from os.path import join, exists
from collections import defaultdict, Counter
from typing import List, Dict, Optional
# ── Lazy / conditional imports ────────────────────────
try:
import numpy as np
HAS_NUMPY = True
except ImportError:
HAS_NUMPY = False
| Form | Syntax | Usage | When to use |
|---|---|---|---|
| Full import | import math |
math.sqrt() |
Default — explicit, no namespace clash |
| Named import | from math import sqrt |
sqrt() |
When using 1–3 specific names frequently |
| Alias | import numpy as np |
np.array() |
Long module names; industry conventions |
| Named alias | from math import factorial as fact |
fact() |
Avoid name conflict or shorten long name |
| Star import | from math import * |
sin(), cos() |
❌ Avoid — use only in REPL or scripts |
The __name__ == '__main__' Guard
Every Python module has a built-in __name__
attribute. When a file is run directly, __name__ equals '__main__'. When it is imported, __name__
equals the module's filename (without .py). This guard lets you write code
that only runs when the file is executed directly — not when imported.
# ── File: calculator.py ───────────────────────────────
def add(a, b):
return a + b
def subtract(a, b):
return a - b
print(f"__name__ = {__name__}")
# Prints '__main__' when run directly
# Prints 'calculator' when imported
# ── This block runs ONLY when the file is executed directly
if __name__ == "__main__":
print("Running calculator directly")
print(add(10, 5)) # 15
print(subtract(10, 5)) # 5
# ── File: main.py ─────────────────────────────────────
import calculator # __name__ = 'calculator', block skipped
print(calculator.add(3, 7)) # 10
# Why this matters:
# Without the guard, importing calculator would also run
# the test code — every time! The guard prevents that.
# Best practice: always wrap executable code in this guard
def main():
"""Entry point for the script."""
print(add(100, 200))
if __name__ == "__main__":
main() # clean, testable entry point
def main(): function, and call main() inside the if __name__ == '__main__': guard. This makes every module both importable and
directly runnable.
Python Standard Library — Batteries Included
Python ships with over 200 modules in its standard library — covering math, file I/O, networking, dates, regular expressions, data structures, testing, and more. No installation required — they're always available. Here are the most commonly used modules:
# math — mathematical functions
import math
print(math.sqrt(144)) # 12.0
print(math.factorial(5)) # 120
print(math.log(math.e)) # 1.0
# random — random number generation
import random
print(random.randint(1, 6)) # dice roll (1–6)
print(random.choice(["a","b","c"])) # random element
items = [1, 2, 3, 4, 5]
random.shuffle(items) # in-place shuffle
# datetime — dates and times
from datetime import date, datetime, timedelta
today = date.today()
now = datetime.now()
deadline = today + timedelta(days=30)
print(f"Today: {today} Deadline: {deadline}")
# os — file system operations
import os
print(os.getcwd()) # current directory
print(os.listdir(".")) # list current dir
print(os.path.join("/data", "file.csv")) # safe path join
# json — JSON encode/decode
import json
data = {"name": "Alice", "age": 25}
json_str = json.dumps(data) # dict → JSON string
parsed = json.loads(json_str) # JSON string → dict
# collections — powerful data structures
from collections import Counter, defaultdict
words = ["apple", "banana", "apple", "cherry"]
freq = Counter(words) # {'apple': 2, ...}
grouped = defaultdict(list)
for w in words:
grouped[w[0]].append(w)
Creating & Using Custom Modules
Creating a custom module is as simple as writing a .py file. Python finds your module by searching the current directory, then
the directories in sys.path. Here's a complete professional example — a
utility module and a main script that imports it.
# ── File: validators.py (your custom module) ─────────
"""
validators.py — reusable input validation utilities.
"""
import re
VERSION = "1.0.0"
def is_valid_email(email: str) -> bool:
"""Return True if email has valid format."""
pattern = r'^[\w\.-]+@[\w\.-]+\.\w{2,}$'
return bool(re.match(pattern, email))
def is_strong_password(pw: str) -> bool:
"""Return True if password has min 8 chars, upper, lower, digit."""
if len(pw) < 8: return False
return (
any(c.isupper() for c in pw) and
any(c.islower() for c in pw) and
any(c.isdigit() for c in pw)
)
def sanitise(text: str) -> str:
"""Strip and lowercase input text."""
return text.strip().lower()
if __name__ == "__main__":
print(is_valid_email("alice@example.com")) # True
print(is_strong_password("Secure1")) # False (<8 chars)
print(is_strong_password("Secure123")) # True
# ── File: app.py (uses the module) ────────────────────
from validators import is_valid_email, is_strong_password, sanitise
email = sanitise(" Alice@EXAMPLE.com ")
print(is_valid_email(email)) # True
pw = "MyP@ss1"
print(is_strong_password(pw)) # False — only 7 chars
Inspecting Modules — dir() & __all__
dir(module) returns a sorted list of all names
defined in a module — great for exploring unfamiliar modules in the REPL. __all__ lets you define exactly which names are exported when someone does
from module import *.
# dir() — list all names in a module
import math
print(dir(math))
# ['__doc__', '__name__', ..., 'acos', 'asin', 'atan',
# 'ceil', 'cos', 'e', 'exp', 'factorial', 'floor', ...]
# Filter out dunder names
public_names = [n for n in dir(math) if not n.startswith("_")]
print(public_names)
# help() — full documentation for a module or function
help(math.sqrt) # shows signature + docstring
# Module attributes
print(math.__name__) # math
print(math.__file__) # path to math.cpython-3X.so (C extension)
print(math.__doc__[:60]) # first 60 chars of module docstring
# ── __all__ — control what is exported ────────────────
# In your module file:
__all__ = ["is_valid_email", "is_strong_password"]
# sanitise is NOT exported with *; still importable by name
# from validators import * → only imports is_valid_email, is_strong_password
# from validators import sanitise → still works explicitly
# Check module search path
import sys
print(sys.path) # Python searches these directories for modules
Module Best Practices
Professional Python code follows conventions that make modules easy to understand, import, and test. These are the rules used by popular open-source projects and the Python standard library itself.
"""
module_best_practices.py
1. Module docstring at the very top
2. Imports in this order: stdlib → third-party → local
3. Constants in UPPER_SNAKE_CASE
4. __all__ to document the public API
5. __name__ guard for executable code
"""
# ── 1. Import ordering (PEP 8) ───────────────────────
# Standard library (always first)
import os
import sys
from datetime import datetime
# Third-party (installed via pip)
import requests
import numpy as np
# Local (your own modules)
from validators import is_valid_email
from utils import format_output
# ── 2. Module-level constants ─────────────────────────
MAX_RETRIES = 3
DEFAULT_TIMEOUT = 30
BASE_URL = "https://api.k2infocom.com"
# ── 3. Define __all__ ─────────────────────────────────
__all__ = ["fetch_data", "process"]
# ── 4. Functions and classes ──────────────────────────
def fetch_data(url, timeout=DEFAULT_TIMEOUT):
"""Fetch data from the given URL with timeout."""
# implementation...
pass
# ── 5. Entry point guard ──────────────────────────────
def main():
"""Script entry point."""
result = fetch_data(BASE_URL)
print(result)
if __name__ == "__main__":
main()
| Rule | Recommendation |
|---|---|
| Import order | stdlib → third-party → local, each group separated by a blank line (PEP 8) |
Avoid import * |
It pollutes the namespace; name origins become unclear |
| Module names | Short, lowercase, no hyphens: myutils.py, not my-utils.py |
| Docstring | Start every module with a docstring describing its purpose |
| __name__ guard | Always wrap executable code — makes every file importable safely |
| __all__ | Define it to document and control the public API of your module |
Practice Python Online — Free Compilers
Don't want to install anything yet? Practice all module examples from this chapter directly in your browser with these free Python environments.
- A module is any
.pyfile. Every file you write is automatically a module. Modules promote code reuse, organisation, and the DRY principle. - Python caches imported modules in
sys.modules— a module's code runs only once no matter how many times it is imported. - Import forms:
import module,from module import name,import module as alias,from module import name as alias. Avoidimport *. __name__equals'__main__'when run directly; equals the module name when imported. Useif __name__ == '__main__':to guard executable code.- Python's standard library has 200+ built-in modules —
math,os,sys,datetime,json,random,re,collections,itertools, and more. - Create custom modules by writing a
.pyfile in the same directory (or anywhere insys.path). dir(module)lists all names;help(module)shows documentation. Use__all__to control what is exported with star import.- PEP 8 import order: stdlib → third-party → local, each group separated by a blank line.
- Best practices: short lowercase module names, module docstring,
__all__,__name__guard, and amain()function as the entry point.
A module is any file with a .py extension
containing Python code — functions, classes, variables, or any Python statements. Every Python file
you write is automatically a module.
Creating one is trivial: just write a .py
file. To use it, place it in the same directory as your script (or anywhere in sys.path) and import it with import filename (without the .py
extension).
import math loads the entire module into its own namespace. You
access its contents with the module prefix: math.sqrt(). This is
the safest form — no namespace pollution and the origin of each name is always clear.
from math import sqrt imports only the
sqrt name directly into the current namespace, so you call it as
sqrt() without a prefix. Convenient for frequently used names, but
the origin is less obvious in larger files.
Every Python module has a __name__ attribute. When you run a file
directly, Python sets __name__ to '__main__'. When the same file is imported by another module, __name__ is set to the module's filename.
The guard if __name__ == '__main__':
ensures that the code inside only runs when the file is executed directly — not when
imported. Without it, importing the module would also execute any test code or script logic, which is
almost never desirable.
Only once. After the first import, Python stores the module object in sys.modules. Every subsequent import of the same module returns the cached version without
re-executing the file's code.
import mymodule # runs mymodule.py
import mymodule # returns cached — code NOT re-run
import sys
print("mymodule" in sys.modules) # True
__all__ is a list defined at module level that specifies which
names are exported when someone does from module import *. Only
the names listed in __all__ are imported; all other module-level
names are excluded.
It does not affect explicit named imports — from module import private_name still works even if private_name is not in __all__.
__all__ is primarily documentation for the public API and a safety
filter for star imports.
__name__ when a Python file is
run directly (not imported)?
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.