Skip to main content

Introductory Courses

Intro to Python

Built-in Func... [python]

Introductory Courses

Intro to Python

Analyzing and... [python]

"Programming with Python" course by the Carpentries

"Programming with Python" course by the Carpentries

Creative Commons License

Libraries

The power of libraries

Most of the power of a programming language lies in its libraries.

A library, or a package is a collection of files (each called a module) that contains functions, types etc. for use in other programs.

  • May also contain data values (e.g., numerical constants) and other things.

  • A good libraries content will be related, but there's no way to enforce that.

The Python standard library is an extensive suite of modules that comes with Python itself.

  • Many additional libraries are available from PyPI (the Python Package Index) or elsewhere.

  • We will later see how to write our own libraries.

Using libraries brings several benefits:

  • We don't have to write everything ourselves, often the task you are trying to accomplish has been done before.

  • Good libraries may also be documented, tested, optimised and continually maintained such that they are more reliable than our own code.

  • Our code is easier to understand to others, since they may be familiar with the library we are using.

  • We can learn good programming practices from libraries.

    • How did they accomplish something?

Libraries and modules

A library is a collection of modules, but the terms are often used interchangeably, especially since many libraries only consist of a single module, so don't worry if you mix the terms.

Importing modules

A module must be imported before it can be used.

  • Use an import statement to load a library module into a program's memory.

  • Once imported, we refer to "things" from the module as module_name.thing_name.

    • Python uses . to mean "part of".

    • Modules can be nested within one another e.g. module_name.submodule.function.

Using math, one of the modules in the standard library:

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

We always have to refer to each item with the module's name.

  • math.cos(pi) won't work: the reference to pi doesn't somehow "inherit" the function's reference to math.

Use help on modules

We can find more out about a module with help, this works just like with a function.

help(math)
Help on module math: NAME math MODULE REFERENCE http://docs.python.org/3/library/math 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 is always available. It provides access to the mathematical functions defined by the C standard. FUNCTIONS acos(x, /) Return the arc cosine (measured in radians) of x. ⋮ ⋮ ⋮

Importing specific items

We can simplify and speed up our programs by importing only what we need.

  • Use the form from ... import ... to load only specific items from a library module.

  • Then refer to them directly without library name as prefix.

from math import cos, pi print('cos(pi) is', cos(pi))
cos(pi) is -1.0

Creating aliases

We can create an alias for a library module when importing it to make our programs clearer and shorter.

  • Use the form import ... as ... to give a library a short alias while importing it.

  • Then refer to items in the library using that shortened name.

import math as m print('cos(pi) is', m.cos(m.pi))
cos(pi) is -1.0
  • Commonly used for libraries that are frequently used or have long names.

    • E.g., the matplotlib plotting library is often aliased as mpl. Overusing aliasing can make programs harder to understand, since readers must learn your program's aliases.

We can, of course, also combine both selective importing and aliasing using from ... import ... as ... to do both things at once.

from matplotlib import pyplot as plt

Will alias just the matplotlib.pyplot module into plt.

Locating the Right Module

You want to select a random character from a string:

bases = 'ACTTGCTTGAC'
  1. Which standard library [stdlib] module could help you?

  2. Which function would you select from that module? Are there alternatives?

  3. Try to write a program that uses the function.

When is Help Available?

When a colleague of yours types help(math), Python reports an error:

NameError: name 'math' is not defined

What has your colleague forgotten to do?

Importing With Aliases

  1. Fill in the blanks so that the program below prints 90.0.

  2. Rewrite the program so that it uses import without as.

  3. Which form do you find easier to read?

import math as m angle = ____.degrees(____.pi / 2) print(____)

Many Ways To Import Libraries

Match the following print statements with the appropriate library calls.

Print commands:

  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 *

Importing specific items

  1. Fill in the blanks so that the program below prints 90.0.

  2. Do you find this version easier to read than preceding ones?

  3. Why wouldn't programmers always use this form of import?

____ math import ____, ____ angle = degrees(pi / 2) print(angle)

Reading Error Messages

  1. Read the code below and try to identify what the errors are without running it.

  2. Run the code, and read the error message. What type of error is it?

from math import log log(0)