Working with libraries¶

##3 Most of the power of a programming language is in its libraries.

  • A library is a collection of files (called modules) that contains functions for use by other programs.

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

    • Library’s contents are supposed to be related, but there’s no way to enforce that.

  • The Python [standard library][stdlib] is an extensive suite of modules that comes with Python itself.

  • Many additional libraries are available from [PyPI][pypi] (the Python Package Index).

  • We will see later how to write new libraries.

Most of the power of a programming language is in its libraries.¶

  • A library is a collection of files (called modules) that contains functions for use by other programs.

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

    • Library’s contents are supposed to be related, but there’s no way to enforce that.

  • The Python [standard library][stdlib] is an extensive suite of modules that comes with Python itself.

  • Many additional libraries are available from [PyPI][pypi] (the Python Package Index).

  • We will see later how to write new libraries.

Note

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 help to learn about the contents of a library module.¶

  • Works just like help for a function.

help(math)

Import specific items from a library module to shorten programs.¶

  • Use 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

Create an alias for a library module when importing it to shorten programs.¶

  • Use 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.

  • But can make programs harder to understand, since readers must learn your program’s aliases.

Exercise: Exploring the Math Module

  1. What function from the math module can you use to calculate a square root without using sqrt?

  2. Since the library contains this function, why does sqrt exist?

Exercise: 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.