#
10 Python Modules#
Many times we will need functions and classes that aren’t provided in the Python Standard library. These additional functions and classes can be imported using modules (single Python script) or packages (a collection of modules).
Installing Packages#
Packages can be installed in a few ways.
Using Anaconda:
conda install package_name
(click here for more information)Using Python’s package installer:
pip install package_name
(click here for more information and here for getting started with pip)Or by running a setup file from the packages source files, which we will not discuss in this course.
The import
Statement#
Modules are imported into the namespace by using the import
statement.
The most basic use case is:
import module_name
where module_name
is the name of the module being imported. To access an object from this module you would use:
module_name.object
The convention is to place import statements at the top of the Python script, or in the first cell of the Jupyter Notebook.
Worked Example - Import math
One module that should be installed by default is the math
module. This module provides mathematical functions and constants, though we will use the NumPy module for much of the same functions instead. Consider the following example of a Python script where the math
module is imported and the factorial
(!) function is used:
import math
print('5! =', math.factorial(5))
5! = 120
You can also import objects directly from the module using:
from module_name import object
Worked Example - Importing factorial directly from math
from math import factorial
print('5! =', factorial(5))
5! = 120
You can also import all of the objects defined in a module by using a *
instead of an object name:
from module_name import *
All objects in the module can now be referred to by name in the global name space. This is not advised in general, as this can cause conflicts in the name space.
Worked Example - Importing all from math
from math import *
print('5! =', factorial(5))
5! = 120
You can import a module under a different name by using an as at the end of the import statement:
import module_name as alias
Normaly this alias
is an abbreviated version of the module being imported. For the modules used in this course, I will be using the standard aliases used (np
for numpy
, plt
for matplotlib.pyplot
, etc).
Worked Example - Importing math as m
We can import the math module under the name of m (math is short enough as is, but just as an example):
import math as m
print('5! =', m.factorial(5))
5! = 120
If you want to read more on modules and packages, you can read on Modules in the Python documentation,