Modules, Packages, and pip
Organizing code across files with import, structuring packages, and managing dependencies with pip and requirements.txt.
2 min read
Every Python file is a module on its own — you can import functions and classes from one file into another, which is how real projects avoid becoming a single unmanageable script.
Importing your own code
Given a file math_utils.py:
# math_utils.py
def square(n):
return n ** 2
PI = 3.14159Another file in the same folder can use it:
# main.py
import math_utils
print(math_utils.square(4)) # 16
print(math_utils.PI) # 3.14159Or import specific names directly, so you don't need to prefix them:
from math_utils import square, PI
print(square(4)) # 16Importing from the standard library
Python ships with a large standard library covering common needs without installing anything extra:
import math
import random
from datetime import datetime
print(math.sqrt(16)) # 4.0
print(random.randint(1, 10)) # a random int between 1 and 10
print(datetime.now()) # current date and timePackages
A package is a folder of modules, marked (in older Python versions, required; in modern Python, optional but still common) by an __init__.py file:
myapp/
__init__.py
models.py
utils.py
from myapp import models
from myapp.utils import helper_functionThis is how larger projects stay organized — related modules grouped into a package instead of dozens of loose .py files in one folder.
Installing third-party packages with pip
The standard library doesn't cover everything. pip, introduced in the setup lesson earlier in this course, installs packages published to the Python Package Index (PyPI):
pip install requestsimport requests
response = requests.get("https://api.example.com/data")
print(response.status_code)requirements.txt
A project shares its exact dependencies through a requirements.txt file rather than assuming everyone remembers what to install:
requests==2.31.0
flask==3.0.0
Generate one from your current environment with pip freeze > requirements.txt, and anyone cloning the project installs the same versions with:
pip install -r requirements.txtPinning exact versions (==2.31.0 rather than leaving it unpinned) means a fresh install months later still gets the same behavior your code was written and tested against, instead of silently picking up breaking changes from a newer release.
Why this structure matters
Splitting code into modules and packages, and declaring dependencies explicitly, is what separates a script that runs on exactly one machine from a project someone else (or you, on a different computer) can clone and run reliably.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.