Python: Modules and Packages

Learn how Python organises reusable code. Modules and packages are the backbone of the entire Python ecosystem, from the standard library to the millions of packages on PyPI.

What is a Module?

A module is simply any file with a .py extension. There is nothing more to the definition than that. When you write a file calledutils.py and put some functions in it, you have created a module. The idea behind modules is to group related code together so it can be reused across different parts of your project without copying and pasting.

Python's standard library is itself just a large collection of modules. When you writeimport math, Python finds the math.py file (or its compiled equivalent) somewhere on your system and loads the objects it defines into your program's namespace.

Importing Modules: import, from, as

Python provides several ways to bring module contents into your code, each with a different trade-off between convenience and clarity.

import module loads the module and binds it to a name in your namespace. You then access anything inside it using dot notation:math.sqrt(9). This makes the origin of every function explicit, which is the safest approach in large codebases.

from module import name pulls a specific name directly into your namespace, so you call sqrt(9)without the prefix. This is convenient but can cause collisions if two modules export the same name. Use it when the imported name is used frequently and its origin is obvious.

import module as alias lets you rename a module on import. This is standard practice for well-known libraries: import numpy as np,import pandas as pd. Pick an alias only if it is widely recognised, otherwise you are just creating confusion.

Three Import Styles

Python

The same function accessed three different ways.

The __name__ == "__main__" Pattern

Every Python file has a built-in variable called__name__. When a file is run directly from the terminal, Python sets__name__to the string "__main__". When the same file is imported as a module by another script,__name__is set to the module's actual name, such as"utils".

The if __name__ == "__main__": guard exploits this to let a file act both as a reusable module and as an executable script. Code inside the guard only runs when you execute the file directly. When another file imports it, the guard block is skipped, so your functions are imported cleanly without triggering any side effects.

Script and Module Dual Role

Python

The same file works as both an importable module and a runnable script.

Creating Your Own Module

Creating a module requires no special syntax. Write your functions, classes, and constants in a .py file and save it. Any other script in the same directory (or anywhere onsys.path) can then import it by name.

The key design principle is single responsibility: each module should cover one coherent area of functionality. A module called validators.pyshould contain validation logic, not database queries. Keeping modules focused makes them easier to test, maintain, and import in isolation.

Packages and the __init__.py File

When your project grows beyond a handful of files, you start grouping modules into directories. A directory becomes a package the moment Python can recognise it as one, which traditionally required placing an__init__.py file inside it. That file can be completely empty, or it can contain initialisation code and import statements that control what gets exposed when someone imports the package.

Python 3.3 introduced "namespace packages," which allow directories without__init__.py to act as packages in some cases. In practice, you should still include the file in any package you distribute or share, because many tools expect it and it signals intent clearly.

Typical Package Layout

A well-structured package organises code by feature or layer.

  • myapp/ - the root package directory
  • myapp/__init__.py - marks the directory as a package
  • myapp/models.py - data model definitions
  • myapp/utils.py - helper functions
  • myapp/api/ - a sub-package for API routes
  • myapp/api/__init__.py - marks api/ as a sub-package

Importing from a Package

Python

Accessing nested modules using dot notation.

pip and Installing Third-Party Packages

pip is Python's package installer. It downloads packages from the Python Package Index (PyPI), which hosts over half a million open-source libraries. Running pip install package-namedownloads the package and installs it so any Python script on your system can import it.

You can also specify a version to keep your environment predictable:pip install requests==2.31.0. Use pip list to see what is installed, pip show package-namefor details about one package, andpip uninstall package-nameto remove it.

Common pip Commands

Python

Managing packages from the terminal.

Virtual Environments with venv

A virtual environment is an isolated Python installation dedicated to a single project. Without one, every package you install goes into your global Python installation, and over time different projects will demand conflicting versions of the same library. A virtual environment solves this by giving each project its own private copies of every package it needs.

The built-in venv module creates virtual environments. Once you activate one, anypip installcommand installs into that environment's private directory, leaving the rest of your system untouched.

Virtual Environment Workflow

Every project should have its own virtual environment.

  • python -m venv venv - create the environment in a folder named "venv"
  • venv\Scripts\activate (Windows) or source venv/bin/activate (macOS/Linux) - activate it
  • pip install ... - all installs now go into the active environment
  • deactivate - return to the global Python environment
  • Add the venv/ folder to .gitignore - never commit it to version control

requirements.txt

A requirements.txt file is a simple text file that lists your project's dependencies, one per line, each with a pinned version number. It is the standard handshake between developers: when someone clones your repository, they runpip install -r requirements.txtand get an environment identical to yours.

The easiest way to generate this file is to install everything your project needs, activate your virtual environment, and then runpip freeze > requirements.txt. This captures the exact version of every installed package.

A Typical requirements.txt

Python

Pinned dependency versions for a reproducible environment.

The Standard Library

Python ships with a large standard library that covers an enormous range of tasks without requiring any additional installation. The community often calls this "batteries included" philosophy. Knowing what is available saves you from writing code from scratch or pulling in dependencies you do not need.

Key Standard Library Modules

These ten modules come up constantly in real-world Python work.

  • math - mathematical functions (sqrt, ceil, floor, log, pi, e)
  • random - random number generation, shuffling, sampling from sequences
  • datetime - date and time arithmetic, parsing, and formatting
  • os - operating system interface: directories, environment variables, processes
  • sys - interpreter state: command-line arguments, sys.path, sys.exit()
  • re - regular expression matching and substitution
  • itertools - fast, memory-efficient iteration tools (chain, product, combinations)
  • functools - higher-order function tools (partial, lru_cache, reduce, wraps)
  • collections - specialised containers (Counter, defaultdict, deque, namedtuple)
  • copy - shallow and deep copying of objects
  • time - time access and conversions; sleep() for pausing execution

Quick Highlights from the Standard Library

Python

One representative snippet from each of four common modules.

Quiz - Test Your Knowledge

Eight questions covering modules, packages, the import system, virtual environments, and the standard library. Some answers require you to think conceptually rather than recall specific syntax.

Knowledge Check

1. What is a Python module?

2. What does the __name__ == "__main__" check accomplish?

3. What file must be present inside a folder to make Python treat it as a package?

4. Which command installs a third-party package from PyPI?

5. What is the primary purpose of a virtual environment?

6. Which standard library module would you use to work with regular expressions?

7. What does "from math import sqrt" accomplish compared to "import math"?

8. What is requirements.txt used for?