11.1 Importing Modules
Any .py file is automatically a "module" that other files are free to import from.
- Writing
import mathgives you access to everything defined inside that module through dot notation, such asmath.sqrt(16). - If you'd rather not type the module name prefix every time,
from math import sqrtimports that one specific name directly into your own file's namespace, letting you simply writesqrt(16). - Finally,
import module as aliaslets you rename a module for convenience at the point of import —import numpy as npis such a common convention in the data-science world that it's practically a second name for the library itself.
11.2 Packages and pip
A package is simply a directory containing several related modules, plus a special __init__.py file that marks the whole directory as importable as one unit — allowing large codebases to be organized hierarchically, such as mypackage.utils.helpers.
pip is Python's standard package manager, used to install third-party libraries from the Python Package Index (PyPI): for example, pip install requests.
Virtual environments (created with venv) give each individual project its own isolated set of installed packages, preventing version conflicts between different projects that happen to live on the same machine.
# Standard Virtual Environment Workflow
# 1. Create an isolated virtual environment
python -m venv .venv
# 2. Activate it:
# Windows (PowerShell):
.venv\Scripts\Activate.ps1
# Mac/Linux:
source .venv/bin/activate
# 3. Install dependencies without affecting system Python:
pip install requests pandas