Importing modules in Python
Start your free 7-days trial now!
A module is a collection of functions, classes, and variables contained within a .py
file. By importing a module, we are able to use the functions, classes, and variables defined in that module, without having to define them ourselves.
Examples
Basic usage
To import the numpy
module and use its abs(~)
method:
Note that when we import modules in this way, we must use dot notation module.function
.
Import with alias
We can import using an alias to save typing:
Import *
We can import all the variables of a module to remove the need for dot notation:
from math import *print(pi)
3.141592653589793
However, this can lead to issues if multiple modules share the same variable names which have different behavior:
from math import *from numpy import *print(pi, log(32, 2))
TypeError: return arrays must be of ArrayType
The math
and numpy
modules both have functions called log
, but they behave differently. Because we imported numpy
after math
, the log
functionality imported from math
is overwritten by the behavior from numpy
, which leads to an issue when we want to use log
according to its definition as per the math
module.
Specific import
To only import specific portions of a module:
from matplotlib import pyplot
Submodules
Modules can contain variables which can in turn refer to other modules:
np.random.random(6)
In the above example, we require two dots as we are calling the random
function within the random
submodule of numpy
.
Importing files from a different folder
By default Python will only search the folder from where the script is run when importing files. To import files located in a different folder:
import syssys.path.insert(1, '/path/where/file/to/import/is/located')import xxxx #insert filename in place of xxxx
Alternatively, if the folder the file to import is located in contains an __init__.py
file you can use:
from path.where.file.located import xxxx #insert filename in place of xxxx