Serverspace Black Friday
DF
February 27, 2023
Updated July 23, 2024

How to write a module in Python 3

Debian Linux Ubuntu

Introduction

Modules in Python are files with a “.py” extension that are coded in Python. Any file written in Python can be referenced as a module.
Several modules are available after installing the Python language. Some modules have to be installed manually.

Installing modules manually we covered in our guide about importing modules into Python 3.
With this guide, you will understand how to:

  • Write a module;
  • Access to modules from other directories;
  • Using an environment variable;
  • Module in Python 3 environment variable.

Preparation for work

You must have a Debian/CentOS//Ubuntu-based distribution set up, setting up a user with sudo privileges. Configured virtual environment Python language. WWe recommend that you prepare in advance before starting work.

Writing and importing modules

The first step is to check the Python version with:

python3 --version

At the moment, the current version is 3.10.6. If you have an older version, then update the package index and software packages using:

sudo apt update && apt upgrade -y

Let's start the virtual environment and use the Vim text editor to create a new file called testingFile.py and add the following lines of code at the very beginning by specifying the shebang. Shebang - using #! specify the path to the Python interpreter, see our instructions for more details.

#!/usr/bin/env python
# Function definition
def test():
print(“This is test file”)

If we run with:

python3 testingFile.py

We will get an empty result. We need to create a second file and name it test2.py and open it with vim and import testingFile.py into the test2.py file and call the test function.

vim test2.py
#!/usr/bin/env python3
#File import
import testingFile
#Calling a function from testingFile
testingFile.test()

We get the following result, as in Screen 1.

Calling a function from an imported module
Screen 1 - Calling a function from an imported module

We are importing the module without using “from testingFile import test”, we need to call the function using the module name. The use of from ... import can be considered in our instructions.

Consider the use of variables in our module, add a line at the very bottom:

#!/usr/bin/env python3
# Function definition
def test():
print("This is test file")
#Assigning a value to a variable
name = "serverspace"

Next, in the test2.py file, at the end, add a line by changing our code to the following form:

#!/usr/bin/env python3
#File import
import testingFile
#Calling a function from testingFile
testingFile.test()
#Calling a print function using a variable
print(testingFile.name)

Output is shown in Figure 2.

Calling a variable from a module
Screen 2 - Calling a variable from a module

Having considered calling the print function and variable, let's look at creating a class and add a few attributes to the class using the following commands.

#!/usr/bin/env python3
# Function definition
def test():
print("This is test file")
#Assigning a value to a variable
name="serverspace"
#Class definition
class TestingClass:
def __init__(self, name, age):
self.name = name
self.age = age
def tell_me_about_TestingClass(self):
print("this class is " + self.name + ".")
print(self.name + "is the testing's name")

Now, using the test2.py file, we will call the initialization function and information about the class:

#!/usr/bin/env python3
#Import module
import testingFile
#Function call
testingFile.test()
#Output information from another module
print(testingFile.name)
#Calling functions from a class
server = testingFile.TestingClass("testingserver", "30 y.o.")
server.tell_me_about_TestingClass()

The result is shown in Screen 3.

Calling functions from the TestingClass class
Screen 3 - Calling functions from the TestingClass class

First, we create a variable called “server”, call the class from the testingFile.py module, assign values ​​for the variable name “testingserver” and the value “30 y.o.” for the age variable.

It is important to keep in mind that a module is a definition, but at the same time it is possible to implement code. Consider a new module example in test3.py

#!/usr/bin/env python3
def TestHello():
print("Testing Hello, World!")
#Calling a function in a module
TestHello()

Import the module into the test4.py file and check the TestHello function call:

#!/usr/bin/env python3
import test3

We get the result in accordance with Screen 4.

4Calling a function from a module
Screen 4 - Calling a function from a module

The reason is simple, inside the test3.py file, we create a function called TestHello and inside it we implement the text printing function. Then we call the created function and import it into the test4.py file. Thus, by running test4.py, we call the text printing function from the TestHello function.

Accessing modules from other directories

Sometimes some modules are useful not only for one project, but also for other projects. For this reason, it is not necessary to store the module in the same project directory. You can create a shared directory and refer to this directory using several methods.

Using an environment variable

If the module is outside the project, use the sys module and use it to specify the path to the environment where the file with the desired module is located. For example, if we create the test5.py file in the home directory, we will not be able to import the test3.py file located in the virtual environment directory. Consider how to specify the path to the test3.py file:

import sys
sys.path.append(‘/root/testing/’)
import test3

And we will get a successful result, as shown in Screen 5.

The result
Screen 5 - The result

We can get a successful result by specifying the correct path to the test3.

Module in Python 3 environment variable

This method is considered an effective solution, the module becomes available for the entire environment and system. Checking Which Path Python Checks With Commands

python3
import sys
print(sys.path)

As a result, we will get the test paths of the Python interpreter, as shown in Screen 6.

Common ways to check the Python interpreter
Screen 6 - Common ways to check the Python interpreter

Select the desired path and copy the test3.py file to the desired path.

cp testing/test3.py /usr/lib/python3.10
python3 test5.py

In the test5.py file, remove the import of the sys module. Let's run the code:


cat test5.py #to make sure the sys import line is removed or commented out
python3 test5.py

We get the output as in Screen 7.

Accessing a module from a shared path
Screen 7 - Accessing a module from a shared path

Copying the module to the Python interpreter's common checkout path proved to be the most efficient. The reason is that in order not to import the sys module in the code files every time and specify the path to the desired module, it is worth copying the desired module to the common path. Do not forget about the backup of the necessary modules, no one excludes the removal of non-standard modules after updating Python packages.

Conclusions

In this guide, we have covered the following options:

  • Creating a module;
  • Importing the created module;
  • Refer to the module by importing the sys module from being in another directory;
  • Adding the created module to the common path of the Python interpreter;
  • Obtained information about common paths when searching for a module using the Python shell.
Vote:
5 out of 5
Аverage rating : 5
Rated by: 1
33145 North Miami, FL 2520 Coral Way apt 2-135
+1 302 425-97-76
700 300
ITGLOBAL.COM CORP
700 300
We use cookies to make your experience on the Serverspace better. By continuing to browse our website, you agree to our
Use of Cookies and Privacy Policy.