One of the key concepts in programming is the creation of simple and easy to maintain code, this is where Python packages come in. A Python package contains code (often written by somebody else) with specific functionalities that allow it to be reused without the need for duplicating code.
For example, if we wanted to write a short Python script that calculates the cosine of an angle we can use the NumPy
package. Before we use the package we need to install it.
Installing Python packages is very simple and one of the most popular package managers to achieve this is pip
. Here, pip
accesses the Python Package Index (PyPI
) that contains a large number of Python packages.
For our example we need the NumPy
package and this can be installed via the following command at the terminal/anaconda prompt (see here for more information about different operating systems):
pip install numpy
Here, pip
will install numpy
and all of the dependencies that it needs to work. We now have our package, but how can we go about using it?
An alternative and popular package maneger is Conda. The benefit of using Conda is that it can install packages written in different langauges (e.g. C, C++ etc) and can also create independent Python environments. You can find out more about Conda here.
In order to use an installed package in our Python script we can make use of the import
statement. It is customary (and recommended) to import
any packages at the start of a Python script. For our example we will need to do this:
import numpy
We can then use the numpy
package and the functions it contains to construct our script:
## Import the entire numpy package
import numpy
angle = numpy.radians(90)
cosine_angle = numpy.cos(angle)
Great! We've now successfully used import
to use our newly installed numpy
package. If we don't want to import
the entire numpy
package (as we have above) we can instead only import
the specific functions we need:
## Import specific functions from numpy
from numpy import cos, radians
angle = radians(90)
cosine_angle = cos(angle)
However, this can sometimes have unintended consequences if these functions share the same name with variables in a longer script. This problem can also arise using from numpy import *
, which imports all functions without the need to use the numpy.
syntax. To get around this it is common to import
packages and rename them:
## Import the specific functions from numpy
import numpy as np
angle = np.radians(90)
cosine_angle = np.cos(angle)
Although our example has used the numpy
package, there are a large number of packages to choose from and each have a customary name that is often used. For example:
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd