As your Python programs grow, keeping everything in a single file becomes unmanageable. Modules let you split code across multiple files, and packages let you organise related modules into directories. Python’s “batteries included” philosophy means the Standard Library ships with powerful modules for file paths, dates, UUIDs, JSON, and more — all ready to use without installing anything extra. This page shows you how to organise your code effectively and leverage the tools Python provides out of the box.
What is a Module?
A module is simply a Python file (.py) containing variables, functions, or classes that you want to reuse across your project.
Create a file named calculator.py:
Import and use it from another file in the same directory:
What is a Package?
A package is a directory containing multiple modules. To turn a folder into a Python package, add an __init__.py file inside it.
The Role of __init__.py
__init__.py serves four purposes:
-
Marks the directory as an importable package.
-
Runs initialisation code when the package is first imported.
-
Creates a public API by re-exporting sub-modules:
Consumers can now write
from mypackage import format_text instead of the full path.
-
Controls wildcard imports using
__all__:
Python’s Standard Library Essentials
pathlib — Modern File Paths
Use pathlib for object-oriented, cross-platform path handling:
os — Operating System Interface
datetime — Dates and Times
uuid — Unique Identifiers
json — JSON Serialisation
string — String Constants
The string module provides useful predefined character sets:
Generate a random password:
Third-Party Packages — requests
While Python’s urllib handles HTTP, the community standard is the requests library for its clean, human-friendly API.
Install it inside your virtual environment first:
Making HTTP Requests
Always check response.status_code before accessing response.json(). A successful response returns 200 for GET and 201 for POST. Use response.raise_for_status() to automatically raise an exception for 4xx/5xx responses.