Libraries

NoteQuestions
  • How do I use code that other people have written?
  • How do I find out what a library provides?
NoteObjectives
  • Explain what libraries and modules are and why they exist.
  • Import a library module and use module.name notation to access its contents.
  • Use help() to explore a module’s contents.
  • Import specific items from a module, and create an alias for a module on import.

Libraries extend what Python can do

Python’s built-in functions cover the basics, but almost everything interesting in scientific computing requires additional tools. A library is a collection of files called modules that contain functions, constants, and other objects written by someone else and packaged for reuse. The Python standard library ships with Python itself and covers an enormous range of tasks. Many more libraries — including NumPy, SciPy, and Matplotlib — are available from PyPI (the Python Package Index) and are installed separately.

The terms library and module are often used interchangeably. Technically a library is a collection of modules, but many libraries consist of a single module, so the distinction rarely matters in practice.

Importing a module

A module must be imported before you can use anything it contains. The import statement loads the module into memory and makes its contents accessible under the module’s name, using dot notation (module_name.thing_name):

import math

print('pi is', math.pi)
print('cos(pi) is', math.cos(math.pi))
pi is 3.141592653589793
cos(pi) is -1.0

The dot notation is intentional: it makes it clear which module a name comes from, and avoids collisions if two modules define something with the same name. Note that math.cos(pi) would fail — the bare name pi is not in scope unless you import it directly; you must write math.pi.

Use help(math) to see the full contents of any imported module, including a description of every function and constant it provides.

Importing specific items

If you only need a few things from a module, you can import them directly using from ... import .... This lets you use their names without the module prefix:

from math import cos, pi

print('cos(pi) is', cos(pi))
cos(pi) is -1.0

The risk is name collisions: if you later define your own variable called pi, or import another pi from a different module, you will silently overwrite the first one. For short scripts where you know exactly what you are importing, this form is fine. For larger programs, import math and explicit math.pi is safer.

Creating an alias on import

For modules with long names that you use frequently, import ... as ... lets you give the module a shorter alias:

import math as m

print('cos(pi) is', m.cos(m.pi))
cos(pi) is -1.0

This is a common convention in scientific Python. You will see import numpy as np and import matplotlib.pyplot as plt throughout these lessons.

CautionChallenge

Exploring the Math Module

  1. What function in math can you use to calculate a square root without using sqrt?
  2. If that alternative exists, why does sqrt also exist?
  1. math.pow(x, 0.5) raises x to the power 0.5, which is the square root.
  2. math.sqrt(x) is more readable when implementing formulas — the intent is immediately clear. The function also has its roots in the C standard library, which Python’s math module mirrors.
CautionChallenge

Locating the Right Module

You want to select a random character from the string:

bases = 'ACTTGCTTGAC'
  1. Which module in the standard library could help?
  2. Which function from that module would you use? Are there alternatives?
  3. Write a short program that uses the function.

The random module is the right choice. The string has 11 characters (indices 0–10), so you can generate a random index and use it to select a character:

from random import randrange

random_index = randrange(len(bases))
print(bases[random_index])
C

random.sample is a more compact alternative that returns a list, so you need to extract the first element:

from random import sample
print(sample(bases, 1)[0])
T
CautionChallenge

When Is Help Available?

A colleague types help(math) and gets:

NameError: name 'math' is not defined

What did they forget to do?

They forgot to import the module first. help(math) requires that math is already loaded into memory:

import math
help(math)
Help on module math:

NAME
    math

MODULE REFERENCE
    https://docs.python.org/3.11/library/math.html
    
    The following documentation is automatically generated from the Python
    source files.  It may be incomplete, incorrect or include features that
    are considered implementation detail and may vary between Python
    implementations.  When in doubt, consult the module reference at the
    location listed above.

DESCRIPTION
    This module provides access to the mathematical functions
    defined by the C standard.

FUNCTIONS
    acos(x, /)
        Return the arc cosine (measured in radians) of x.
        
        The result is between 0 and pi.
    
    acosh(x, /)
        Return the inverse hyperbolic cosine of x.
    
    asin(x, /)
        Return the arc sine (measured in radians) of x.
        
        The result is between -pi/2 and pi/2.
    
    asinh(x, /)
        Return the inverse hyperbolic sine of x.
    
    atan(x, /)
        Return the arc tangent (measured in radians) of x.
        
        The result is between -pi/2 and pi/2.
    
    atan2(y, x, /)
        Return the arc tangent (measured in radians) of y/x.
        
        Unlike atan(y/x), the signs of both x and y are considered.
    
    atanh(x, /)
        Return the inverse hyperbolic tangent of x.
    
    cbrt(x, /)
        Return the cube root of x.
    
    ceil(x, /)
        Return the ceiling of x as an Integral.
        
        This is the smallest integer >= x.
    
    comb(n, k, /)
        Number of ways to choose k items from n items without repetition and without order.
        
        Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates
        to zero when k > n.
        
        Also called the binomial coefficient because it is equivalent
        to the coefficient of k-th term in polynomial expansion of the
        expression (1 + x)**n.
        
        Raises TypeError if either of the arguments are not integers.
        Raises ValueError if either of the arguments are negative.
    
    copysign(x, y, /)
        Return a float with the magnitude (absolute value) of x but the sign of y.
        
        On platforms that support signed zeros, copysign(1.0, -0.0)
        returns -1.0.
    
    cos(x, /)
        Return the cosine of x (measured in radians).
    
    cosh(x, /)
        Return the hyperbolic cosine of x.
    
    degrees(x, /)
        Convert angle x from radians to degrees.
    
    dist(p, q, /)
        Return the Euclidean distance between two points p and q.
        
        The points should be specified as sequences (or iterables) of
        coordinates.  Both inputs must have the same dimension.
        
        Roughly equivalent to:
            sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
    
    erf(x, /)
        Error function at x.
    
    erfc(x, /)
        Complementary error function at x.
    
    exp(x, /)
        Return e raised to the power of x.
    
    exp2(x, /)
        Return 2 raised to the power of x.
    
    expm1(x, /)
        Return exp(x)-1.
        
        This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.
    
    fabs(x, /)
        Return the absolute value of the float x.
    
    factorial(n, /)
        Find n!.
        
        Raise a ValueError if x is negative or non-integral.
    
    floor(x, /)
        Return the floor of x as an Integral.
        
        This is the largest integer <= x.
    
    fmod(x, y, /)
        Return fmod(x, y), according to platform C.
        
        x % y may differ.
    
    frexp(x, /)
        Return the mantissa and exponent of x, as pair (m, e).
        
        m is a float and e is an int, such that x = m * 2.**e.
        If x is 0, m and e are both 0.  Else 0.5 <= abs(m) < 1.0.
    
    fsum(seq, /)
        Return an accurate floating point sum of values in the iterable seq.
        
        Assumes IEEE-754 floating point arithmetic.
    
    gamma(x, /)
        Gamma function at x.
    
    gcd(*integers)
        Greatest Common Divisor.
    
    hypot(...)
        hypot(*coordinates) -> value
        
        Multidimensional Euclidean distance from the origin to a point.
        
        Roughly equivalent to:
            sqrt(sum(x**2 for x in coordinates))
        
        For a two dimensional point (x, y), gives the hypotenuse
        using the Pythagorean theorem:  sqrt(x*x + y*y).
        
        For example, the hypotenuse of a 3/4/5 right triangle is:
        
            >>> hypot(3.0, 4.0)
            5.0
    
    isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
        Determine whether two floating point numbers are close in value.
        
          rel_tol
            maximum difference for being considered "close", relative to the
            magnitude of the input values
          abs_tol
            maximum difference for being considered "close", regardless of the
            magnitude of the input values
        
        Return True if a is close in value to b, and False otherwise.
        
        For the values to be considered close, the difference between them
        must be smaller than at least one of the tolerances.
        
        -inf, inf and NaN behave similarly to the IEEE 754 Standard.  That
        is, NaN is not close to anything, even itself.  inf and -inf are
        only close to themselves.
    
    isfinite(x, /)
        Return True if x is neither an infinity nor a NaN, and False otherwise.
    
    isinf(x, /)
        Return True if x is a positive or negative infinity, and False otherwise.
    
    isnan(x, /)
        Return True if x is a NaN (not a number), and False otherwise.
    
    isqrt(n, /)
        Return the integer part of the square root of the input.
    
    lcm(*integers)
        Least Common Multiple.
    
    ldexp(x, i, /)
        Return x * (2**i).
        
        This is essentially the inverse of frexp().
    
    lgamma(x, /)
        Natural logarithm of absolute value of Gamma function at x.
    
    log(...)
        log(x, [base=math.e])
        Return the logarithm of x to the given base.
        
        If the base not specified, returns the natural logarithm (base e) of x.
    
    log10(x, /)
        Return the base 10 logarithm of x.
    
    log1p(x, /)
        Return the natural logarithm of 1+x (base e).
        
        The result is computed in a way which is accurate for x near zero.
    
    log2(x, /)
        Return the base 2 logarithm of x.
    
    modf(x, /)
        Return the fractional and integer parts of x.
        
        Both results carry the sign of x and are floats.
    
    nextafter(x, y, /)
        Return the next floating-point value after x towards y.
    
    perm(n, k=None, /)
        Number of ways to choose k items from n items without repetition and with order.
        
        Evaluates to n! / (n - k)! when k <= n and evaluates
        to zero when k > n.
        
        If k is not specified or is None, then k defaults to n
        and the function returns n!.
        
        Raises TypeError if either of the arguments are not integers.
        Raises ValueError if either of the arguments are negative.
    
    pow(x, y, /)
        Return x**y (x to the power of y).
    
    prod(iterable, /, *, start=1)
        Calculate the product of all the elements in the input iterable.
        
        The default start value for the product is 1.
        
        When the iterable is empty, return the start value.  This function is
        intended specifically for use with numeric values and may reject
        non-numeric types.
    
    radians(x, /)
        Convert angle x from degrees to radians.
    
    remainder(x, y, /)
        Difference between x and the closest integer multiple of y.
        
        Return x - n*y where n*y is the closest integer multiple of y.
        In the case where x is exactly halfway between two multiples of
        y, the nearest even value of n is used. The result is always exact.
    
    sin(x, /)
        Return the sine of x (measured in radians).
    
    sinh(x, /)
        Return the hyperbolic sine of x.
    
    sqrt(x, /)
        Return the square root of x.
    
    tan(x, /)
        Return the tangent of x (measured in radians).
    
    tanh(x, /)
        Return the hyperbolic tangent of x.
    
    trunc(x, /)
        Truncates the Real x to the nearest Integral toward 0.
        
        Uses the __trunc__ magic method.
    
    ulp(x, /)
        Return the value of the least significant bit of the float x.

DATA
    e = 2.718281828459045
    inf = inf
    nan = nan
    pi = 3.141592653589793
    tau = 6.283185307179586

FILE
    /opt/hostedtoolcache/Python/3.11.15/x64/lib/python3.11/lib-dynload/math.cpython-311-x86_64-linux-gnu.so

CautionChallenge

Importing With Aliases

  1. Fill in the blanks so that the program prints 90.0.
  2. Rewrite it using import without as.
  3. Which form do you find easier to read?
import math as m
angle = ____.degrees(____.pi / 2)
print(____)
import math as m
angle = m.degrees(m.pi / 2)
print(angle)
90.0

Without the alias:

import math
angle = math.degrees(math.pi / 2)
print(angle)
90.0

When you wrote the code yourself, the short alias feels natural. Months later, or when reading someone else’s code, the spelled-out math.degrees is clearer — especially when there are many modules involved.

CautionChallenge

Many Ways to Import

Match each print statement to the library call that makes it work.

Print statements:

  1. print("sin(pi/2) =", sin(pi/2))
  2. print("sin(pi/2) =", m.sin(m.pi/2))
  3. print("sin(pi/2) =", math.sin(math.pi/2))

Library calls:

  1. from math import sin, pi
  2. import math
  3. import math as m
  4. from math import *
  1. → library calls 1 or 4 (both make sin and pi available as bare names)
  2. → library call 3 (uses the alias m)
  3. → library call 2 (uses the full module name math)
CautionChallenge

Importing Specific Items

  1. Fill in the blanks so that the program prints 90.0.
  2. Is this version easier to read than the previous ones?
  3. Why wouldn’t programmers always use this form?
____ math import ____, ____
angle = degrees(pi / 2)
print(angle)
from math import degrees, pi
angle = degrees(pi / 2)
print(angle)
90.0

This form is often the most readable for short scripts. The main reason not to use it everywhere is name collisions: if you also define a variable called degrees, or import degrees from another library, the later import silently replaces the earlier one, which can cause subtle bugs.

CautionChallenge

Reading Error Messages

  1. Read the code below and try to identify the error without running it.
  2. Run it and read the error message. What type of error is it?
from math import log
log(0)
  1. The logarithm is only defined for positive numbers, so log(0) is mathematically undefined.
  2. Python raises a ValueError: math domain error. The error type tells you the function received a value outside its valid domain.
TipKey Points
  • A library is a collection of modules containing reusable functions, constants, and other objects.
  • Use import module_name to load a module; access its contents with module_name.thing_name.
  • Use help(module_name) to see what a module provides.
  • Use from module import item to import specific items and use them without the module prefix.
  • Use import module as alias to create a short alias; stick to widely recognised conventions.