Skip to content
skillbld
Day 10 of 14 30 minimportstdlibpip

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.

Mind map · click a dot to fold, drag to pan

Importing a module

main.py · editable
Output
Press Run to execute this code.

There are a few ways to import:

main.py · editable
Output
Press Run to execute this code.
FormYou writeBest for
import mathmath.sqrt(9)Clear origin of each name
from math import sqrtsqrt(9)A few names you use a lot
import datetime as dtdt.date.today()Long module names

A tour of the standard library

main.py · editable
Output
Press Run to execute this code.
ModuleUse it for
math, statisticsMaths and averages
randomRandom numbers, shuffling, sampling
datetimeDates, times and durations
collectionsCounter, defaultdict, deque
jsonReading and writing JSON
pathlib, osFiles and folders
csvSpreadsheet-style data

Your own modules

Any .py file is a module. Put helper functions in one file and import them from another:

Sketch
A project folder containing main.py and a package folder shop with __init__.py, pricing.py (def add_tax) and cart.py. main.py imports from cart.py, and cart.py imports add_tax from pricing.py.
pricing.py
TAX_RATE = 0.2
 
def add_tax(price):
    return round(price * (1 + TAX_RATE), 2)
main.py
from pricing import add_tax
 
print(add_tax(10))   # 12.0

A 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__:

main.py · editable
Output
Press Run to execute this code.

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:

terminal
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 versions
weather.py
import requests
 
r = requests.get("https://api.github.com")
print(r.status_code)

Recap

  • import module, from module import name and import module as alias bring code in.
  • The standard library covers maths, randomness, dates, JSON, files and much more, with nothing to install.
  • Your own .py files are modules; folders of them are packages.
  • if __name__ == "__main__": separates "run directly" code from importable code.
  • Use pip inside a virtual environment for third-party packages.

Knowledge check

Test what you learned

5 questions · pick an answer to see if you're right

0/5
  1. 1

    After "import math", how do you call the square root function?

  2. 2

    What is a module?

  3. 3

    What is the standard library?

  4. 4

    What does "if __name__ == '__main__'" let you do?

  5. 5

    Why create a virtual environment before using pip?

Finished today's lesson?