Modules and Libraries#

A module (or library) is a collection of functions and other objects which are meant to be re-used in multiple programs and / or by multiple users.

In Python, a module consist of one or more Python files. To be used in a program, whole modules or parts of modules are imported.

Writing and using own modules in Python#

Example module code#

Suppose we have a file called three_calc.py with the following contents:

def add_three_numbers(x, y, z):
    """Add all three arguments."""
    return x + y + z


def multiply_three_numbers(x, y, z):
    """Multiply all three arguments."""
    return x * y * z

Importing a whole module#

We can import the module three_calc and use the functions above as members of the module:

import three_calc

a = three_calc.add_three_numbers(4, 5, 6)
b = three_calc.multiply_three_numbers(1, 2, 3)

Note that for using the functions from the three_calc, we need to prepend three_calc. to the function name.

Importing parts of a module#

We can also import only some elements from the module:

from three_calc import add_three_numbers

c = add_three_numbers(1, 2, 3)

Aliasing modules or parts of modules#

We could also give an alias to the imported objects:

import three_calc as tc
from three_calc import multiply_three_numbers as mtn

a = tc.add_three_numbers(1, 2, 3)
b = mtn(4, 5, 6)

Existing modules#

There are many modules which are either provided with the programming language (mostly called standard library) or provided by others (called third-party libaries).

Python has a large standard library which provides functionality like string manipulation, file-system operations, or math.

Let’s have a look at the math module.

The Python math module#

import math

alpha_degrees = 30.0  # degrees
alpha_radians = math.pi / 180.0 * alpha_degrees

print("cos(30) =", math.cos(alpha_radians))
print("sin(30) =", math.sin(alpha_radians))
cos(30) = 0.8660254037844387
sin(30) = 0.49999999999999994