4: Packages and Libraries
- Page ID
The core installation of python has a variety of functions and code, and these can be extended by installing packages that have specific functionalities. This is very important when working with sensors and the like as a package is the easiest way to get the code for the sensor. The basic idea is to only run the code you need, and so there is a two part process to using packages. First, you must install them, and then you must call them within your program. Most IDEs have a utility for installing packages, but you can also do it from the command line.
Python Package Index
the python package Index (https://pypi.org/) has a list of over 270,000 projects (as of 11/2/2020). Type in the search window BME680 (an Airquality sensort that measured VOCs, humidity, pressure and temperature) and you can find 19 projects with code that are related to this sensor.
If we look at the adafruit-circuitpython-bme680 3.2.4 we see the following command
sudo pip3 install adafruit-circuitpython-bme680 #Installs the adafruit-circuitpyton-bme680 package sudo pip3 install numpy #Installs the numpy array handling package
Note, pip allows you to install code from PyPI and is installed on python 3 versions that are >=3.4
Each package has a series of scripts called modules. Lets look at the numpy package that allows you to work with arrays and matrices.
Now that the package is installed, you need to import it into your script for it to work [package=the name of your package]. Once the package is imported to the program you can use the modules by referring to the package.
import package package.module1 #calls the first module within the package package.module2 #calls the second module within the package import package as pg #you can assign a package a shorthand alias that allows you to call it. pg.module1 import numpy as np # it is common to import numpy as np, and this way other programmers can tell what the module is related to np.array[1,2,3] from package import module1 #this allows you to call the module without specifiying the package
Note, the disadvantage of the last technique is you may forget you are using a module within a defined package. This is especially an issue if someone else is looking at your code, and did not see that you had imported the module from the package
Numpy stands for Numeric Python and can perform calculations over arrays
numpy arrays can only have one data type
numpy arrays are actually a new python type
import numpy as np
print(arrayname.ndim) # gives the dimension of the array
You can define the dimensions with the ndim= function
import numpy as np darray = np.array([1, 2, 3, 4], ndmin=5) print(darray) print('number of dimensions :', darray.ndim)