Libraries
Overview
Teaching: 10 min
Exercises: 0 minQuestions
How can I use software that other people have written?
How can I find out what that software does?
Objectives
Explain what software libraries are and why programmers create and use them.
Write programs that import and use libraries from Python’s standard library.
Find and read documentation for standard libraries interactively (in the interpreter) and online.
Most of the power of a programming language is in its libraries.
A library in Python contains a set of tools (called functions) that perform tasks on our data. Importing a library is like getting a piece of lab equipment out of a storage locker and setting it up on the bench for use in a project. Once a library is set up, it can be used or called to perform many tasks. Scientific Python distributions like Anaconda or Enthought come with many useful Libraries.
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 them.
A program must import a library module before using it.
Python doesn’t load all of the libraries available to it by default. We have to
add an import
statement to our code in order to use library functions. To import
a library, we use the syntax import libraryName
.
Each time we call a function that’s in a library, we use the syntax
LibraryName.FunctionName
.
Adding the library name with a .
before the
function name tells Python where to find the function.
Then refer to things from the module as libraryName.thing_name
.
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
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 introspection to learn about the contents of a library.
With introspection we can learn how to use a library even if we don’t have access to a manual or online documentation.
help
provides an overview of the module just as it does for functions.
help(math)
Help on module math:
NAME
math
MODULE REFERENCE
http://docs.python.org/3.5/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(...)
acos(x)
Return the arc cosine (measured in radians) of x.
⋮ ⋮ ⋮
With dir we can display all functions of a library.
The functions starting and ending with ___
are not intended for use by general users.
dir(math)
['__doc__',
'__file__',
'__loader__',
'__name__',
'__package__',
'__spec__',
'acos',
'acosh',
'asin',
'asinh',
'atan',
'atan2',
'atanh',
'ceil',
'copysign',
'cos',
'cosh',
'degrees',
'e',
'erf',
'erfc',
'exp',
'expm1',
'fabs',
'factorial',
'floor',
'fmod',
'frexp',
'fsum',
'gamma',
'gcd',
'hypot',
'inf',
'isclose',
'isfinite',
'isinf',
'isnan',
'ldexp',
'lgamma',
'log',
'log10',
'log1p',
'log2',
'modf',
'nan',
'pi',
'pow',
'radians',
'sin',
'sinh',
'sqrt',
'tan',
'tanh',
'tau',
'trunc']
If we are interested in a specific fucntion we can use help
on that fucntion.
help(log)
Help on built-in function log in module math:
log(...)
log(x[, base])
Return the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x.
Import specific items from a library module to shorten programs.
We use from ... import ...
to load only specific items from a library module.
Then we can 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
Create an alias for a library module when importing it to shorten programs.
We use import ... as ...
to give a library a short alias while importing it.
Then we can 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
This is commonly used for libraries that are frequently used or have long names.
* E.g., matplotlib
plotting library is often aliased as mpl
.
But this can make programs harder to understand since readers must learn your program’s aliases.
Exploring the Math Module
- What function from the
math
module can you use to calculate a square root without usingsqrt
?- Since the library contains this function, why does
sqrt
exist?Solution
- Using
help(math)
we see that we’ve gotpow(x,y)
in addition tosqrt(x)
- The
sqrt(x)
function (like much of themath
library) has it’s origins in C’s math library. Consequently, it might be somewhat faster thanpow(x,y)
. Also, it might be more readable thanpow(x, 0.5)
when implementing equations. However,sqrt(x)
doesn’t support negative arguments.
Locating the Right Module
You want to select a random character from a string:
bases = 'ACTTGCTTGAC'
- Which standard library module could help you?
- Which function would you select from that module? Are there alternatives?
- Try to write a program that uses the function.
Solution
The random module seems like it could help you.
The string has 11 characters, each having a positional index from 0 to 10. You could use
random.randrange
function (or the aliasrandom.randint
if you find that easier to remember) to get a random integer between 0 and 10, and then pick out the character at that position:from random import randrange random_index = randrange(len(bases)) print(bases[random_index])
or more compactly:
from random import randrange print(bases[randrange(len(bases))])
Perhaps you found the
random.sample
function? It allows for slightly less typing:from random import sample print(sample(bases, 1)[0])
Note that this function returns a list of values. We will learn about lists in episode 11.
There’s also other functions you could use, but with more convoluted code as a result.
Jigsaw Puzzle (Parson’s Problem) Programming Example
Rearrange the following statements so that a random DNA base is printed and its index in the string. Not all statements may be needed. Feel free to use/add intermediate variables.
bases="ACTTGCTTGAC" import math import random ___ = random.randrange(n_bases) ___ = len(bases) print("random base ", bases[___], "base index", ___)
Solution
import math import random bases = "ACTTGCTTGAC" n_bases = len(bases) idx = random.randrange(n_bases) print("random base", bases[idx], "base index", idx)
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?
Solution
Importing the math module (
import math
)
Importing With Aliases
- Fill in the blanks so that the program below prints
90.0
.- Rewrite the program so that it uses
import
withoutas
.- Which form do you find easier to read?
import math as m angle = ____.degrees(____.pi / 2) print(____)
Solution
import math as m angle = m.degrees(m.pi / 2) print(angle)
can bewritten as
import math angle = math.degrees(math.pi / 2) print(angle)
Since you just wrote the code and are familiar with it, you might actually find the first version easier to read. But when trying to read a huge piece of code written by someone else, or when getting back to your own huge piece of code after several months, non-abbreviated names are often easier, except where there are clear abbreviation conventions.
There Are Many Ways To Import Libraries!
Match the following print statements with the appropriate library calls.
Print commands:
print("sin(pi/2) =",sin(pi/2))
print("sin(pi/2) =",m.sin(m.pi/2))
print("sin(pi/2) =",math.sin(math.pi/2))
Library calls:
from math import sin,pi
import math
import math as m
from math import *
Solution
- Library calls 1 and 4. In order to directly refer to
sin
andpi
without the library name as prefix, you need to use thefrom ... import ...
statement. Whereas library call 1 specifically imports the two functionssin
andpi
, library call 4 imports all functions in themath
module.- Library call 3. Here
sin
andpi
are referred to with a shortened library namem
instead ofmath
. Library call 3 does exactly that using theimport ... as ...
syntax - it creates an alias formath
in the form of the shortened namem
.- Library call 2. Here
sin
andpi
are referred to with the regular library namemath
, so the regularimport ...
call suffices.
Importing Specific Items
- Fill in the blanks so that the program below prints
90.0
.- Do you find this version easier to read than preceding ones?
- Why wouldn’t programmers always use this form of
import
?____ math import ____, ____ angle = degrees(pi / 2) print(angle)
Solution
from math import degrees, pi angle = degrees(pi / 2) print(angle)
Most likely you find this version easier to read since it’s less dense. The main reason not to use this form of import is to avoid name clashes. For instance, you wouldn’t import
degrees
this way if you also wanted to use the namedegrees
for a variable or function of your own. Or if you were to also import a function nameddegrees
from another library.
Reading Error Messages
- Read the code below and try to identify what the errors are without running it.
- Run the code, and read the error message. What type of error is it?
from math import log log(0)
Solution
- The logarithm of
x
is only defined forx > 0
, so 0 is outside the domain of the function.- You get an error of type “ValueError”, indicating that the function received an inappropriate argument value. The additional message “math domain error” makes it clearer what the problem is.
Key Points
Most of the power of a programming language is in its libraries.
A program must import a library module in order to use it.
Use
help
to learn about the contents of a library module.Import specific items from a library to shorten programs.
Create an alias for a library when importing it to shorten programs.