Packages

Jon Reades

Advanced Laziness!

Packages (also called modules or libraries) are bundles of useful, related functions and constants.

Importing a Package

If a package is installed, then it’s as simple as:

import <packagename>

You normally do this at the start of a program so that it’s easy to see what the program requires to run:

import math
print(math.pi) # Prints 3.141592653589793

What Can a Package Do?

There are many ways to find this out:

  1. Read the documentation
  2. Search Google, and
  3. Search StackOverflow

There’s even a web site python.readthedocs.io.

But we can also ask the package:

import math
dir(math)
# ['__doc__', '__file__', '__name__', '__package__', ..., 
# 'log', 'log10', 'log1p', 'modf', 'pi', ...]
help(math.log10)

So…

  1. dir(<package name>) lists all ‘things’ that <package> contains.
  2. By convention, things that start with __ are ‘private’ (you shouldn’t change them) and things that start and end with __ are metadata (e.g. __version__).
  3. Everything else you can interrogate with help(<package name>.<thing in package>).

With help(math.log10) you get an answer like this:

Help on built-in function log10 in module math:

log10(x, /)
    Return the base 10 logarithm of x.

With help(math.pi) you get an answer Help on float object

Why Namespaces Matter

Consider this:

import math
pi = 4
print(math.pi)
print(pi)

So math.pi and pi are not the same variable!

More Laziness: Aliases

Programmers hate typing more than they have to:

import math
r = 5
area = math.pi * r**2
ln = math.log(area)
print(ln)

So we can use an alias instead:

import math as m
r = 5
area = m.pi * r**2
ln = m.log(area)
print(ln)

You will see this used a lot with more complex libraries like Pandas (pd), Geopandas (gpd), and PySAL (ps).

Importing Part of a Package

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:

from math import pi, log10
print(pi)
help(log10)

This import pi and log10 from math into the ‘main’ namespace.

Gotcha!

Notice the subtle differences here:

Approach 1

pi = 3.1415
print(pi)      # 3.1415

import math as m
print(m.pi)    # 3.141592...
print(pi)      # 3.1415
print(math.pi) # Error!

Approach 2

pi = 3.1415
print(pi) # 3.1415

from math import pi
print(pi)      # 3.141592...
print(m.pi)    # Error!
print(math.pi) # Error!

Packages Make Your Life Easier

Resources

A bit of a mish-mash of different explanations: