COMP1531

2.5 - Python - Packages

 

Importing libraries

Python comes packaged with a number of standard libraries (e.g. "math"). However, many libraries that you may want to use have to be installed for usage.

 

Installing is quite easy due to the pip program, which makes installations of python dependencies doable in just a single line of code. pip is a package installer for python.

Importing libraries

To use the `numpy` library we need to first install it on our machine.

import numpy as np

a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])

print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim) 
$ pip3 install numpy

Virtual Environments

A virtual environment is a tool that helps to keep dependencies required by different projects separate by creating isolated python virtual environments for them.

 

You can read more about them here and here.

 

You may be asked a question about them on the exam, but you will never be required to use them.

 

They are often required for use with CI/CD

Virtual Environments

Even though we know how to install modules, we now run into a problem:

  • How do I easily share the modules that I've installed with my team members?
  • How do I ensure my project doesn't end up accidentally using installed modules from other projects, and vice versa?

 

Virtual Environments

pip3 install virtualenv
python3 -m virtualenv venv/
source venv/bin/activate

# Do stuff

pip3 freeze > requirements.txt # Save modules
pip3 install -r requirements.txt # Install modules

deactivate

COMP1531 21T1 - 2.5 - Python - Packages

By haydensmith

COMP1531 21T1 - 2.5 - Python - Packages

  • 413