One of the best features of Python, as we saw in deliveries previous Python programming course using Linux, is that The code can be reused in other parts of the application or in other applications.
In this post we will see How to use programs within other programs without having to paste or type the code into themThis is useful because Python has a number of libraries for specific tasks that free us from the work of "reinventing the wheel."
Python programming course using Linux
Up until now, we've defined a function and called it when we needed it. Now we're going to introduce the concept of a module. A module is a file in which functions and classes are defined and variables are declared. Since modules are independent files, using them to build large projects makes maintenance and updating easier.
Python includes a number of modules for a diverse variety of tasks, and we can also create our own.
The advantages of using modules are:
- Reuse: We can write a program once that performs a specific task (for example, calculating a tax) and call it to be used in as many programs as we need that function without having to rewrite the code.
- Order: The modules help to divide the parts of the project logically, making it possible for anyone with a minimal knowledge of Python to understand what each part of the program does.
- Maintenance: The shorter the code, the easier it is to find errors and make modifications.
- Scalability: In large projects, modular construction makes it easier to divide and re-unify the work.
- Bookstores: Python provides programmers with a wide range of modules, from game creation to large Artificial Intelligence projects.
To correctly build a Python project in modules, you need to divide and save the different parts in files with the .py extension. Ideally, you should follow these criteria:
- Identify parts of the code that perform similar functions: For example, we can group data capture in one module, processing in another, and output and storage in another.
- Assign Descriptive names: The idea is that anyone can tell at a glance what each module does. If it's a data validation module, it's more useful to call it validation.py than 1234.py.
We're going to create a module named mostrar_distro.py. This is the module:
This module creates a function to print the name of a distribution that will be specified in the program that imports the function along with the text "The best distro is... Don't doubt it"
This is the application that calls the module.
This program calls the module we previously saved, invokes the distro function, and executes it with the parameter "Ubuntu". If we change anything in the module, such as the text displayed next to the distribution name, it will be reflected in the program.
The import instruction
As we saw in the code, to import a module we do
import nombre_modulo
The extension is not addedn.py
However, we don't need to import the entire module. We can import specific parts:
from nombre_modulo import elemento1, elemento2
To save typing or avoid name conflicts, it is possible to assign an alias to the imported module.
import nombre_moulo as nm
Using nm in any reference to the module in the code name.
If we don't want to reference the module every time we invoke one of its elements, we can do the following:
from nombre_modulo import *
This will allow us to call each element of the module from the code as if we had defined it within the code itself. However, this could create conflicts with existing elements.
Location of the modules
In the first article of the course, we explained the concept of virtual environments. This practice, which is mandatory in Ubuntu and other Linux distributions and optional in Windows, creates a file structure that includes locations for storing modules. Generally, a module can be stored in three locations:
- The directory where the main program that calls the module is located.
- If you installed it using a package manager, it's in the lib folder of the virtual environment.
- In user-defined directories, the location is specified in the import command.
Types of modules:
- Standard modules: They are included with the Python installation and serve a wide range of common programmer tasks, such as generating random numbers. They require no additional configuration and are developed by the same developers as the language.
- User-developed modules: They respond to the specific needs of a project, and if they are made available to other users in forums or download sites, there is no guarantee of official support or updates.
- Maintained by third parties: They are installed using specific package managers and fulfill common needs of many users not covered by standard modules, such as sending messages via WhatsApp. Although in many cases they are maintained by companies or responsible users with complete and up-to-date documentation, malicious packages have also been found.
Some examples of standard modules are:
- Math: It provides support for mathematical functions such as root calculations, trigonometry, logarithms, and constants.
- Random: It is used for generating random numbers and randomly selecting elements.
- Datetime: Calendar management, working with dates and times, and calculating time differences.
- You: It deals with the application's interaction with the operating system, including working with files, directories, and environment variables.
The pip package manager
Like so many names in the world of free software, pip is the recursive acronym in English for pip package installer. It is the official tool for installing third-party created modules. We can see the list of available packages here
The basic commands are:
Install module
pip3 install nombre_modulo
Update module
pip3 install --upgrade nombre_modulo.
Uninstall module
pip3 uninstall nombre_modulo
In the next installment we will continue with the course.