Situatie
Libraries are collections of shared code. They’re common in Python, where they’re also called “modules,” but they’re also ubiquitous across other programming languages. A library defines functions that any programmer can use in their own programs, similar to how a public library offers anyone access to its materials.
The advantage of using libraries is that you can save time and effort by not having to code your own solutions. Libraries tend to be better tested and debugged than anything you could come up with. They will also let you do more than you could on your own.
There are numerous libraries in Python for tasks such as graphics, game development, and more. My favorite libraries tend to be for data analysis. Python is especially popular for statistics and data science due to the large number of libraries available for these tasks.
There are several ways to install Python libraries on your system. If you’re using a Linux distribution, there will often be Python libraries included in your distro’s package manager. For example, on Debian and Ubuntu systems, the libraries will often start with “python-” or “python3-“. This will install the library system-wide, so you’ll need to have administrative access.
If you don’t have root or administrative access on your system, there are still ways to install Python libraries locally.
You can use the pip tool to install Python libraries listed in the Python Package Index (PyPi).
For example, to install NumPy:
pip instlall numpy
You can install libraries on a per-project basis in virtual environments using the virtualenv utility. You can take the concepts of virtualenv further using Mamba, which happens to be my method of choice. Mamba is a tool popular among data scientists and analysts that allows you to create project-specific environments.
I already have a Mamba environment for statistical computing populated with several libraries that are popular for data analysis. I can activate it at the shell:
mamba activate stats
A lot of Python libraries will come with the language. This is a point of pride for the Python culture. The Python Standard Library has lots of modules for everything from interacting with the operating system to working with times and dates. This is why Python programmers like to say that the language has “batteries included.”
Importing a whole Python Library
To import a whole Python library in a script or in the interactive Python mode, use the import command.
For example, to import the NumPy module, use this command:
import numpy
To get at these functions, you can call the module you just imported. It’s effectively an object, if you understand how object-oriented programming works. These functions are methods that are private to the object we just created by importing the library.
For example, to calculate the arithmetic mean or average of an array using NumPy, we’d type this:
numpy.mean(numbers)
This calls the mean function in NumPy.
You might think that typing “numpy” every time you want to access the functions is a lot, and you’re right. You can import libraries with other names as a shortcut. A common example you’ll see with NumPy is shortening the name to “np” in import statements:
import numpy as np
You can now refer to numpy as “np.” Let’s rewrite that earlier mean calculation:
np.mean(numbers)
Importing Part of a Library (Interactive Python Only!)
A lot of times, when you’re working in an interactive Python section, such as in the standard interactive Python interpreter or IPython, you’ll often want to import only one or two functions from a large library, especially if you want to use them repeatedly during a session. This is also easy to do in Python.
To import a single function from NumPy into the main namespace, you can use this construction:
from library import function
For example, to import the mean function from NumPy:
from numpy import mean
from numpy import mean, median
With these functions imported, you won’t have to preface them with “numpy” or “np.” You can just use them as if they were part of the default Python functions.
For example, to calculate the mean of an array of numbers
mean(numbers)
And the median:
median(numbers)
Importing functions by themselves is better-suited to interactive Python sessions because it saves on typing. You can do it in a script, but it’s not recommended. You might end up overwriting the namespace that’s used for a default Python function. This might cause a bug in your script. If you ask for help online in a forum or IRC chat, the other Pythonistas might get stumped. This is why you should avoid these kinds of imports in scripts as much as possible.
Creating and Importing Your Own Python Libraries
It’s also easy to import your own Python libraries. You can do it without having to be an expert in Python. All you need is a text editor and the ability to use a terminal. Python modules are just ultimately collections of functions defined in Python. You can just create a file ending in .py, the same way you were writing a script. If you’ve created your own Python functions, you can stick them in a file and import them, the same as with any other built-in or installed Python module.
chmod +x my_library.py
You can import the library using the methods described earlier. If you’re in the same directory as the module, you can just use import statements. For example, to import the library:
import my_library
If the library is in another directory, there are a couple of ways to change the search path. The first method is to use the PYTHONPATH environment variable. It’s a list of directories that Python will use to look for modules. You can modify this in your system shell either at the command line or in a startup file such as the .bashrc file in Bash. It’s a list of directories separated by a colon (:) character, similar to the PATH environment variable on Linux systems.
At the Linux shell, you can examine it with the echo command:
echo $PYTHONPATH
To change it, it’s best to append it.
export PYTHONPATH=”$PYTHONPATH:/path/to/my/modules”
This will ensure that any existing module search path is preserved before adding your own directory.
You can also modify the search path using the built-in sys module. Just import it in an interactive Python session:
import sys
Then examine it:
Since there’s no real distinction between a Python script and a module or library, you can easily convert one to the other. It’s good programming style to break operations into smaller functions. You can also call them from another script or interactive section, but what if you have a script? You can just define the script’s operations in a “main” function.
This will check if the Python interpreter is executing the script as a script instead of importing. You can then put everything you want after this section to execute in the script, while leaving the functions to be possibly imported in another script or interactive session.
With the ability to use modules, you can tap into Python’s vast array of available modules. You’ll be able to do more than you thought you ever could by yourself. You’ll save a lot of time and effort over coding from scratch.
Leave A Comment?