Packages (also called modules or libraries) are bundles of useful, related functions and constants.
Package | Does |
---|---|
os |
Operating System stuff (paths, processes, etc.) |
csv |
Reading and Writing CSV files. |
math |
Maths constants and functions. |
statistics |
Simple statistical tests & measures. |
urllib |
URL Reading (e.g. web pages). |
numpy |
Numerical Python (scientific computing). |
scipy |
Scientific Python (more scientific computing) |
sklearn |
Machine learning, clustering, etc. |
If a package is installed, then it’s as simple as:
You normally do this at the start of a program so that it’s easy to see what the program requires to run:
There are many ways to find this out:
There’s even a web site python.readthedocs.io.
But we can also ask the package:
dir(<package name>)
lists all ‘things’ that <package>
contains.__
are ‘private’ (you shouldn’t change them) and things that start and end with __
are metadata (e.g. __version__
).help(<package name>.<thing in package>)
.With help(math.log10)
you get an answer like this:
With help(math.pi)
you get an answer Help on float object
…
Consider this:
So math.pi
and pi
are not the same variable!
Programmers hate typing more than they have to:
So we can use an alias instead:
You will see this used a lot with more complex libraries like Pandas (pd
), Geopandas (gpd
), and PySAL (ps
).
Sometimes even that is too much typing… or sometimes we only really want one or two things from a much larger package. In that case we can select these specifically:
This import pi
and log10
from math
into the ‘main’ namespace.
Notice the subtle differences here:
A bit of a mish-mash of different explanations:
Packages • Jon Reades