Stand on the shoulders of giants. Import code from Python's huge standard library, organise your own code into modules, and install packages with pip.
By the end of today you can
- Import modules with import and from … import
- Use popular standard-library modules like math, random, datetime and collections
- Split your own code into modules and packages
- Install third-party packages with pip inside a virtual environment
Python comes with batteries included: hundreds of ready-made modules for math, dates, randomness, files, the web and more. Today you'll learn to use them, organise your own code the same way, and install extra packages.
Importing a module
There are a few ways to import:
| Form | You write | Best for |
|---|---|---|
import math | math.sqrt(9) | Clear origin of each name |
from math import sqrt | sqrt(9) | A few names you use a lot |
import datetime as dt | dt.date.today() | Long module names |
A tour of the standard library
| Module | Use it for |
|---|---|
math, statistics | Maths and averages |
random | Random numbers, shuffling, sampling |
datetime | Dates, times and durations |
collections | Counter, defaultdict, deque |
json | Reading and writing JSON |
pathlib, os | Files and folders |
csv | Spreadsheet-style data |
Your own modules
Any .py file is a module. Put helper functions in one file and import them from another:
TAX_RATE = 0.2
def add_tax(price):
return round(price * (1 + TAX_RATE), 2)from pricing import add_tax
print(add_tax(10)) # 12.0A package is a folder of modules (traditionally with an __init__.py file), so you can write from shop.pricing import add_tax.
Run as a script, or import as a module?
A module's code runs when it's imported. Guard the "run me directly" part with __name__:
Installing packages with pip
The Python Package Index (PyPI) has hundreds of thousands of packages. Install them with pip, ideally inside a virtual environment so each project keeps its own packages:
python -m venv .venv # create a virtual environment
source .venv/bin/activate # macOS/Linux
.venv\Scripts\activate # Windows
pip install requests # install a package
pip freeze > requirements.txt # record exact versionsimport requests
r = requests.get("https://api.github.com")
print(r.status_code)Recap
import module,from module import nameandimport module as aliasbring code in.- The standard library covers maths, randomness, dates, JSON, files and much more, with nothing to install.
- Your own
.pyfiles are modules; folders of them are packages. if __name__ == "__main__":separates "run directly" code from importable code.- Use
pipinside a virtual environment for third-party packages.
Knowledge check
Test what you learned
5 questions · pick an answer to see if you're right
- 1
After "import math", how do you call the square root function?
- 2
What is a module?
- 3
What is the standard library?
- 4
What does "if __name__ == '__main__'" let you do?
- 5
Why create a virtual environment before using pip?
Finished today's lesson?